2014-03-14 28 views
2

這是從編譯好的代碼。它將文件名打印在目錄中,並在其前面有一個字母選項:根據文件類型(o),可選擇d,f,lo。但是,我在目錄/etc/network上測試了它,它有一個名爲run的符號文件,它顯示爲d?我已經嘗試重新安排if-statements的順序,但是這也給我們帶來不滿意的結果。我使用不正確?C:<sys/stat.h>函數S_ISLNK,S_ISDIR和S_ISREG行爲奇怪嗎?

while ((ent = readdir (dp)) != NULL) { 
    lstat(ent->d_name, &st); 
    if (col){ 
      if(S_ISDIR(st.st_mode)){ 
        printf("d\t"); 
        } 
      else if (S_ISREG(st.st_mode)){ 
        printf("f\t"); 
        } 
      else if (S_ISLNK(st.st_mode)){ 
        printf("l\t"); 
      } 
      else { 
        printf("o\t"); 
      } 
    } 

回答

1

這可能工作作爲一種替代方案:

if(col){ 

      if(ent->d_type == DT_DIR) 
       printf("d "); 
      else if(ent->d_type == DT_LNK) 
       printf("l "); 
      else if(ent->d_type == DT_REG) 
       printf("f "); 
     } 
4

在這一行:lstat(ent->d_name, &st);dp->d_name包含文件的唯一名稱,您需要將文件的完整路徑傳遞給lstat()這樣的:

char full_path[512] = "DIR_PATH"; //make sure there is enough space to hold the path. 
    strcat(full_path, ent->d_name); 
    int col = lstat(full_path, &st); 

BTW,S_ISDIRS_ISLNK等是POSIX宏而不是函數。