2015-02-10 58 views
1

我試圖創建一個方法,將執行一些系統調用。它應該顯示每個文件的所有者和八進制代碼。但不知何故,我不能走。它顯示的用戶名登錄,因爲每個文件的所有者列出目錄並顯示每個文件的詳細信息。所有者,八進制權限和文件名使用c

listContents(char * dir) { 

    struct dirent *direntp; 
    DIR *dirp; 

    if ((dirp = opendir(dir)) == NULL) 
    { 
     perror ("Failed to open directory"); 
     return 1; 
    } 

    while((direntp=readdir(dirp))!=NULL) { 
     struct stat fileInfo; 
     if (stat(direntp->d_name, &fileInfo) == 0); 
     { 
      struct passwd * pInfo = getpwuid(fileInfo.st_uid); 
      if(pInfo!=NULL) 
      { 
       printf("owner is : %s\toctal permisions is: %o\n", pInfo->pw_name, fileInfo.st_mode); 
      } 
     } 
    } 

    while ((closedir(dirp) == -1) && (errno == EINTR)) ; 

    return 0; 
} 
+0

我試着修復縮進給你,但完全失去了。請自己糾正。 – 2015-02-10 21:14:20

+0

它不正確的所有者。但我認爲你需要寫'fileInfo.st_mode&0777'而不是'fileInfo.st_mode'來顯示權限。 – 2015-02-10 21:21:00

+0

潛在的無限循環while((closedir(dirp)== -1)&&(errno == EINTR));'簡單地使用'closedir(dirp);' – chux 2015-02-10 22:16:42

回答

1

你有一個錯誤:

if (stat(direntp->d_name, &fileInfo) == 0); { 

shuld是

if (stat(direntp->d_name, &fileInfo) == 0) { 

但你的版本會在當前目錄下,因爲只有工作您正在使用stat其中第一個參數應該是文件的整個路徑,而不僅僅是名稱。 我添加了一點修改後的代碼:

list_contents (char *dir) { 
    struct dirent *direntp; 
    DIR *dirp; 
    char path[PATH_MAX + 1]; 
    char fpath[PATH_MAX + 1]; 

    if ((dirp = opendir(dir)) == NULL) { 
     perror ("Failed to open directory"); 
     return 1; 
    } 

    strcpy(path, dir); 
    strcat(path, "/"); 

    while (NULL != (direntp = readdir(dirp))) { 
     struct stat fileInfo; 
     strcpy(fpath, path); 
     strcat(fpath, direntp->d_name); 

     if (stat(fpath, &fileInfo) == 0) { 
      struct passwd * pInfo = getpwuid(fileInfo.st_uid); 
      if(pInfo != NULL) { 
       printf("%s - owner is : %s\toctal permisions are: %o\n", direntp->d_name, pInfo->pw_name, fileInfo.st_mode); 
      } 
     } 
    } 

    closedir(dirp); // edited as chux proposed 

    return 0; 
}