我们如何在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. 如何读取多个目录并读取Perl中子目录的内容?
- 3. 如何读取Perl中目录的内容?
- 4. 读取目录中的所有文件内容
- 5. Xcode OSX - 如何从usb中读取目录的内容
- 6. Apache骆驼读取目录并获取文件内容
- 7. 递归读取目录并有选择地获取内容
- 8. 从linux中的目录中读取文件的顺序
- 9. 安全地阅读目录内容
- 10. XNA C#读取目录内容的问题
- 11. 使用shell脚本读取目录的内容
- 12. 在与ActiveSync同步时读取PDA目录的内容
- 13. Haskell中的目录内容
- 14. 目录的Python的焦油提取不提取该目录中的内容
- 15. 读取Linux内核参数
- 16. 在Linux中删除内容但不是目录?
- 17. 读取XML内容
- 18. 在matlab中读取目录
- 19. linux命令将文件夹的内容复制到根目录
- 20. Linux Shell脚本:将目录的内容列入文件
- 21. 网络目录的内容
- 22. 带FilePathResult的内容目录
- 23. 阅读我的项目的webcontent文件夹内的目录的内容
- 24. 获取目录内容,但不显示目录
- 25. matla中的目录的内容
- 26. 目录中的linux mkdir目录
- 27. 如何从index.js中获取相同目录中的内容?
- 28. 使用json,读取目标文件中的内容c
- 29. 阅读listView的内容,并根据目录的内容在另一个listView中显示丢失的项目
- 30. 如何删除Linux中多个目录中存在的文件的内容
我们展示的你在哪里打,使一些人可以帮你的代码。并用当前的代码解释问题。 – Mahesh 2011-04-20 18:18:58