2009-10-27 53 views
1

你知道为什么某些文件不被这个节目上市,即使他们是“正规”?:列表常规文件(不包括目录)的问题

#include <stdio.h> 
#include <sys/types.h> 
#include <sys/param.h> 
#include <sys/stat.h> 
#include <dirent.h> 

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 [email protected] 28 denis staff 952 27 oct 22:20 .. 
2423204 [email protected] 1 denis staff 6148 27 oct 21:41 .DS_Store 
2423206 [email protected] 1 denis staff 895 27 oct 19:57 ef efeff 
2423183 [email protected] 1 denis staff 895 27 oct 19:57 ffffff 
2423216 [email protected] 1 denis staff 895 27 oct 19:57 ffffff - copie 
2423436 drwxr-xr-x 2 denis staff 68 27 oct 21:57 folder 
2423180 [email protected] 1 denis staff 38 27 oct 21:32 printiie.tt 
2423682 [email protected] 1 denis staff 895 27 oct 19:57 test.c 
2423208 [email protected] 1 denis staff 34 27 oct 21:39 z 

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

回答

5

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

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

..你就会明白为什么。

+0

谢谢!我得到这个消息为未列出的文件: 错误:统计(printiie.tt):没有这样的文件或目录 目前我不明白为什么,因为这些文件存在... – Denis

+1

它在我看起来像目录你正在用'opendir'检查和'stat'正在查看的当前工作目录不一样。 'opendir(“。”)'会发生什么? – caf

+0

经过一些测试,我得到这个:note:file-> d_name =>。 note:info.st_mode => 16877 note:file-> d_name => .. note:info.st_mode => 16832 很奇怪,因为删除.DS_Store后,程序检测到0个文件。 – Denis

-2

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

编辑: 这个答案是不是代码,而是:

Actually I just would like to list the name of each file, but without directories.

如果他采取了同样的方法,因为我,他会他的问题就迎刃而解了。

+1

-1:这不是关于代码问题的答案。 –