簡體   English   中英

S_ISDIR()的問題導致結果為C(可能是因為stat()未正確設置其結構?)

[英]Issue with S_ISDIR() result in C (maybe because stat() isn't setting its struct properly?)

我希望我的程序獲取目錄,然后打印該目錄的內容並聲明每個項目是否為目錄。 如果我給它一個包含文件F1.txt和F2.txt以及文件夾D1,D2和D3的目錄,則應打印:

F1.txt不是目錄
F2.txt不是目錄
D1是目錄
D2是目錄
D3是目錄

char* curr[100];
DIR* dirp = opendir(name);
struct dirent* x;
struct stat fstat;

//go to each file til readdir gives NULL
while((x = readdir(dirp)) != NULL) {

  //store name of file
  curr[0] = (x -> d_name);

  //ignore files starting with "."
  if(*curr[0] == '.')
    continue;

  //set status
  stat(curr[0], &fstat);

  //print file name
  printf("%s", *curr);

  //check if it's a directory and print result
  if(S_ISDIR(fstat.st_mode))
    printf(" is directory\n");
  else
    printf(" is not directory\n");
}

這表明所有文件都不是目錄。 如果我刪除忽略以“。”開頭的文件的部分,則說明F1.txt,F2.txt和D1不是目錄,而。,D2,D3和..是目錄(按此順序)。 這使我認為問題出在stat調用,而不是我對宏的使用,但是我在這里很困惑,所以我不知道。

您正在向stat傳遞文件名,但是它需要文件的路徑。 如果您檢查stat的返回值,您會發現它僅對起作用. .. ,因為它們存在於任何目錄中。

規范的答案:永遠不要試圖理解程序中出現錯誤情況的行為。 (即使是最微小的事物)(最遲),添加代碼以檢查所有函數的返回值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM