2015-08-18 27 views
1

計劃:檢查,如果該文件是目錄或不

#include<stdio.h> 
#include<stdlib.h> 
#include<dirent.h> 
#include<sys/stat.h> 
int main(int argc, char *argv[]) 
{ 
    DIR *dp; 
    struct dirent *dirp; 
    struct stat stbuf; 
    if (argc != 2) 
     printf("usage: ls directory_name\n"); 

    if ((dp = opendir(argv[1])) == NULL) 
     printf("can’t open %s", argv[1]); 

    while ((dirp = readdir(dp)) != NULL){ 
     stat(dirp->d_name,&stbuf); 
     if(S_ISDIR(stbuf.st_mode)){ 
      printf("Directory: "); 
     } 
     printf("%s\n",dirp->d_name); 
    } 

    closedir(dp); 
    exit(0); 
} 

輸出:

$ ./a.out test/ 
dir3 
d 
c 
Directory: . 
Directory: a 
Directory: .. 
Directory: dir4 
Directory: dir2 
Directory: dir0 
Directory: b 
Directory: e 
Directory: dir1 
$ 

以下是該目錄下的「測試」包含的文件列表。

$ ls -F test/ 
a b c d dir0/ dir1/ dir2/ dir3/ dir4/ e 
$ 

的預期結果是,如果該文件是目錄輸出將是「目錄:DIR1 /」。否則只有文件名。 但是,該程序的輸出不符合預期。該程序是否包含任何錯誤?有沒有讓我知道。

在此先感謝...

+0

[在C中訪問目錄]的可能重複(http://stackoverflow.com/questions/3536781/accessing-directories- in-c) – Kninnug

+3

(1)你需要檢查'stat()'的返回值來查看是否有錯誤。 (2)你正在調用'stat()'(例如)'dir2',但你需要通過'test/dir2'。 – psmears

+0

我建議你檢查一下'stat'是否返回,我敢打賭它的大部分名字都是'-1'(意思是失敗)。 –

回答

2

讓我們把它分解爲若干步驟:

  1. 你開始從一些目錄中的程序。該目錄將成爲進程當前工作目錄(CWD)。

  2. 您可致電目錄test上的opendir。這實際上是CWD中的目錄test

  3. 您可以撥打readdir以獲取目錄中的第一個條目。

  4. 這個第一項是.目錄,它是的簡稱,當前目錄,所有的目錄都有它。

  5. 您可以撥打stat.,這意味着您可以在CWD上致電stat。它當然成功並且stat填充了CWD所有細節的結構。

  6. 下一次迭代,您將獲得條目a,並且您在該條目上調用stat。但由於CWD中沒有a,因此stat呼叫失敗。但是,您不檢查該內容,並使用之前的調用(來自.目錄的成功stat)填寫的stat結構。

等等......

你需要告訴stat尋找在給定的目錄,而不是CWD的條目。讓您前綴與您傳遞給opendir目錄中的條目

  • 格式的字符串:這基本上只有兩種方式來完成。例如。

    char path[PATH_MAX]; 
    snprintf(path, sizeof(path), "%s/%s", argv[1] ,dirp->p_name); 
    if (stat(path, &stbuf) != -1) 
    { 
        // `stat` call succeeded, do something 
    } 
    
  • 調用opendir後,但循環該目錄之前,改變CWD:

    // Opendir call etc... 
    
    chdir(argv[1]); 
    
    // Loop using readdir etc. 
    

另外,從目錄中啓動程序要檢查:

$ cd test 
$ ../a.out . 
相關問題