我們如何在Linux中使用C語言讀取目錄的內容(子目錄和文件名)。讀取linux中的目錄內容
4
A
回答
4
相關函數是opendir,readdir和closedir。我建議「男人opendir」等
2
這裏是代碼將這樣做(取自link),希望它會讓你開始你在找什麼。
#include <ftw.h>
#include <stdio.h>
#include <sys/stat.h>
int list(const char *name, const struct stat *status, int type);
int main(int argc, char *argv[]) {
if(argc == 1)
ftw(".", list, 1);
else
ftw(argv[1], list, 1);
return 0;
}
// FTW_F The object is a file
// FTW_D ,, ,, ,, ,, directory
// FTW_DNR ,, ,, ,, ,, directory that could not be read
// FTW_SL ,, ,, ,, ,, symbolic link
// FTW_NS The object is NOT a symbolic link and is one for
// which stat() could not be executed
int list(const char *name, const struct stat *status, int type) {
if(type == FTW_NS)
return 0;
if(type == FTW_F)
printf("0%3o\t%s\n", status->st_mode&0777, name);
if(type == FTW_D && strcmp(".", name) != 0)
printf("0%3o\t%s/\n", status->st_mode&0777, name);
return 0;
}
編輯:FTW是什麼是用來走路的文件系統,更多信息關於它請參見其手冊頁ftw man page
+2
+1以彌補無謂的-1。 'ftw' **確實**讀取一個目錄。 – 2011-04-20 19:01:10
+0
加1到R.爲好評,ftw和nftw都讀取目錄。 – 2011-04-20 20:48:34
6
這裏是一個遞歸程序打印所有子目錄和文件的名稱遞歸。
用法:./a.out路徑名稱
對於作爲命令行參數提供的初始路徑名,未檢查錯誤條件。
基本代碼流程:
讀取當前目錄中的所有條目。
如果它是目錄名稱,它的名稱被添加到路徑名稱並且函數被遞歸調用。
打印文件的其他名稱。有關特定功能
細節可以在各自的手冊頁被引用爲指向的dmuir:
#include<sys/stat.h>
#include<unistd.h>
#include<dirent.h>
#include<error.h>
int read(char *pth)
{
char path[1000];
strcpy(path,pth);
DIR *dp;
struct dirent *files;
/*structure for storing inode numbers and files in dir
struct dirent
{
ino_t d_ino;
char d_name[NAME_MAX+1]
}
*/
if((dp=opendir(path))==NULL)
perror("dir\n");
char newp[1000];
struct stat buf;
while((files=readdir(dp))!=NULL)
{
if(!strcmp(files->d_name,".") || !strcmp(files->d_name,".."))
continue;
strcpy(newp,path);
strcat(newp,"/");
strcat(newp,files->d_name);
printf("%s\n",newp);
//stat function return a structure of information about the file
if(stat(newp,&buf)==-1)
perror("stat");
if(S_ISDIR(buf.st_mode))// if directory, then add a "/" to current path
{
strcat(path,"/");
strcat(path,files->d_name);
read(path);
strcpy(path,pth);
}
}
}
int main(int argc,char *argv[])
{
read(argv[1]);
}
相關問題
- 1. Cordova讀取目錄內容
- 2. PHP - 讀取目錄的內容
- 3. 如何讀取多個目錄並讀取Perl中子目錄的內容?
- 4. PHP函數讀取子目錄內容
- 5. 讀取特定目錄中文件的內容
- 6. 讀取目錄中的所有文件內容
- 7. Xcode OSX - 如何從usb中讀取目錄的內容
- 8. 如何讀取Perl中目錄的內容?
- 9. PHP Zip:提取目錄中的內容
- 10. 從目錄中讀取所有文件內容 - php
- 11. 如何在Linux內核3.2.x中的自定義系統調用期間讀取目錄的內容
- 12. Apache駱駝讀取目錄並獲取文件內容
- 13. 遞歸讀取目錄並有選擇地獲取內容
- 14. 從Linux中形成的文本文件中讀取內容bash
- 15. 從linux中的目錄中讀取文件的順序
- 16. 安全地閱讀目錄內容
- 17. 小巧的框架 - 無法讀取目錄內容 - winioerror
- 18. 使用shell腳本讀取目錄的內容
- 19. 在與ActiveSync同步時讀取PDA目錄的內容
- 20. 如何使用python-ldap讀取活動目錄的內容?
- 21. XNA C#讀取目錄內容的問題
- 22. Haskell中的目錄內容
- 23. 在Linux中枚舉目錄內容的函數有哪些?
- 24. 在Linux中檢查目錄內容的腳本
- 25. 閱讀目錄內容而不是zip文件內容
- 26. 目錄的Python的焦油提取不提取該目錄中的內容
- 27. Linux目錄卡在只讀中
- 28. 如何在bash中輸出目錄中不可讀的內容
- 29. 讀取Linux內核參數
- 30. Linux內核讀取功能
我們展示的你在哪裏打,使一些人可以幫你的代碼。並用當前的代碼解釋問題。 – Mahesh 2011-04-20 18:18:58