问题
I want my program to take a directory, then print the contents of that directory and state whether or not each item is a directory or not. If I give it a directory containing files F1.txt and F2.txt and folders D1, D2, and D3, it should print:
F1.txt is not directory
F2.txt is not directory
D1 is directory
D2 is directory
D3 is directory
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");
}
This prints saying that all the files are not directories. If I remove the part that ignores files starting with ".", it says F1.txt, F2.txt and D1 are not directories, and that ., D2, D3, and .. are directories (in that order). That makes me think the issue is with the stat call rather than my use of the macros, but I'm pretty confused here so I don't know.
回答1:
You're passing stat the name of the file, but it needs a path to the file. If you check the return value for stat, you'll see that it's only succeeding for . and .., because they exist in any directory.
Canonical answer: Do not ever try to understand the behavior of a program that blows through error conditions. As soon as it's even the tiniest bit mysterious (at the latest), add code to check the return values of all functions.
来源:https://stackoverflow.com/questions/19505846/issue-with-s-isdir-result-in-c-maybe-because-stat-isnt-setting-its-struct