2009-10-27 57 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:這不是關於代碼問題的答案。 –