仅列出常规文件(没有目录)问题

你知道为什么这个程序没有列出某些文件,即使它们是“常规”的吗?:

#include  #include  #include  #include  #include  int main(void) { DIR *dh = opendir("./"); // directory handle struct dirent *file; // a 'directory entity' AKA file struct stat info; // info about the file. while (file = readdir(dh)) { stat(file->d_name, &info); printf("note: file->d_name => %s\n", file->d_name); printf("note: info.st_mode => %i\n", info.st_mode); if (S_ISREG(info.st_mode)) printf("REGULAR FILE FOUND! %s\n", file->d_name); } closedir(dh); return 0; } 

执行完这个程序后,我得到了这个:

 note: file->d_name => . note: info.st_mode => 16877 note: file->d_name => .. note: info.st_mode => 16832 note: file->d_name => .DS_Store note: info.st_mode => 16832 note: file->d_name => ef efeff note: info.st_mode => 16832 note: file->d_name => ffffff note: info.st_mode => 16832 note: file->d_name => ffffff - copie note: info.st_mode => 16832 note: file->d_name => folder note: info.st_mode => 16832 note: file->d_name => printiie.tt note: info.st_mode => 16832 note: file->d_name => test.c note: info.st_mode => 33188 REGULAR FILE FOUND! test.c note: file->d_name => z note: info.st_mode => 33188 REGULAR FILE FOUND! z 

如您所见,程序只看到两个文件。 但是每个文件都是常规文件,并且只有一个文件夹。

这是shell命令的复制过去: $ ls -lai

 total 64 2421444 drwxr-xr-x 10 denis staff 340 27 oct 22:19 . 2416789 drwxr-xr-x@ 28 denis staff 952 27 oct 22:20 .. 2423204 -rw-r--r--@ 1 denis staff 6148 27 oct 21:41 .DS_Store 2423206 -rwxr-xr-x@ 1 denis staff 895 27 oct 19:57 ef efeff 2423183 -rwxr-xr-x@ 1 denis staff 895 27 oct 19:57 ffffff 2423216 -rwxr-xr-x@ 1 denis staff 895 27 oct 19:57 ffffff - copie 2423436 drwxr-xr-x 2 denis staff 68 27 oct 21:57 folder 2423180 -rw-r--r--@ 1 denis staff 38 27 oct 21:32 printiie.tt 2423682 -rw-r--r--@ 1 denis staff 895 27 oct 19:57 test.c 2423208 -rwxr-xr-x@ 1 denis staff 34 27 oct 21:39 z 

我只想列出每个文件的名称,但没有目录。 我在Mac OS X上工作,但我不认为这可能是问题的原因。

看起来某些文件的stat函数失败了,所以info结构没有被更新,并且仍然有".."的数据。 将该行替换为:

 if (stat(file->d_name, &info)) { printf("error: stat(%s): %s\n", file->d_name, strerror(errno)); continue; } 

..你会明白为什么。

我曾经不得不列出目录中的每个yml文件,包括子目录。 它是在Win XP: system("dir C:\Path\To\File\*.yml /B /S >> list.txt"); 然后我会解析list.txt以获取所有这些。 一行是一个文件。 容易,但不便携。 也就是前段时间 – 现在我可能会尝试提升。

编辑:这个答案与代码无关,但是:

实际上我只想列出每个文件的名称,但没有目录。

如果他采取与我相同的方法,他将解决他的问题。