2014-04-25 21 views
1

我想遞歸讀取目錄並打印出一些關於這些文件的元數據。我有程序工作的單一目錄。但是對於子目錄,當我應用stat方法時,文件不斷給出錯誤,不存在這樣的文件或目錄。統計功能不適用於子目錄?

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

void scan(const char *dir) // process one directory 
{ 
    DIR *dp; 
    struct dirent *de; 
    struct stat sbuf; 

    dp = opendir(dir); 
if(dp == NULL) 
{ 
//  perror(dir); 
    printf("Cannot open directory %s\n",dir); 
    return; 
} 

while(1) 
{ 
    const char * d_name; 
    de = readdir(dp); 
    if(de == NULL) 
      break;//Empty Directory 

    d_name = de->d_name; 
    printf("d_name: %s\n",d_name); 
//  if(strcmp(d_name,"..") != 0 && strcmp(d_name,".") != 0) 
//    printf("%s/%s\n",dir,d_name);//Print File or Directory 


    if(stat(de->d_name, &sbuf)) 
    { 
    //  perror(de->d_name); 
      printf("Error in stat %s\n",de->d_name); 
      continue; 
    } 

if(S_ISDIR(sbuf.st_mode) && (strcmp(d_name,"..") != 0 && strcmp(d_name,".") != 0)) 
{ 
//  printf("d_name: %s\n",d_name); 
    printf("d\t"); 
} 
else 
    if (strcmp(d_name,"..") == 0 || strcmp(d_name,".") == 0) 
    { 
    //    printf("d_name: %s\n",d_name); 
    //    continue; 
    } 
else 
{ 
    //  printf("d_name tab: %s\n",d_name); 
    printf("\t"); 
} 

    if(strcmp(d_name,"..") != 0 && strcmp(d_name,".") != 0) 
     printf("%lu\t%s\n", (unsigned long) sbuf.st_size, de->d_name); 

     if(de->d_type == DT_DIR) 
     { 
      if(strcmp(d_name,"..") != 0 && strcmp(d_name,".") != 0) 
      { 
        char path[1024]; 
        snprintf(path,1024,"%s/%s",dir,d_name); 
        scan(path); 

      } 
    } 

} 

    closedir(dp); 
} 

int main(int argc, char *argv[]) 
{ 
    int i; 
    scan(argv[1]); 

    return 0; 
} 

回答

2

你忘了前面加上你的dir您​​時stat ING。您仍然在您的原始目錄中,因爲您沒有在其他地方編輯chdir

+0

但我從來沒有預設第一個目錄。 – user3213348

+0

從技術上講,這也是錯誤的,但是如果你的第一個目錄是當前目錄,你可以避開它。 –

+0

因此,例如,如果目錄是/ home/usr,文件是f​​ile.c,我會在stat中傳遞/home/usr/file.c文件? – user3213348