我正在尝试找到某个路径是否是目录。
我正在使用以下代码中<sys/stat.h>
中存在的统计功能:
int isDir(char *path){
printf("%sn", path);
struct stat file;
stat(path, &file);
printf("%in", file.st_mode);
int x;
x = S_ISDIR(file.st_mode);
return x;
}
// I tried this function with the following code.
printf("%in", isDir("/home/aladdin"));
printf("%in", isDir("/home/aladdn"));
我在PC上的用户名是aladdin
,因此,第一个应该工作并等于1
,第二个应该打印一个0
,因为没有名为aladdn
的用户。
因此,运行以前的代码给出
/home/aladdin
16832
1
/home/aladdn
16832
1
对怎么了?
您必须检查Stat返回代码。如果Stat失败,它将不会修改您的文件结构内容,在这种情况下,IS_DIR似乎返回true。
所以,而不是您当前的行stat(path, &file);
,有行:
if (stat(path, &file) == -1) return 0;
...当然,您可能应该以某种方式报告错误,具体取决于您的要求,但是简单的更改将解决您的功能。
关于为什么要获得相同的结果,我认为C将结构像该结构一样,除非您明确初始化它们,并且使用这种用法,该结构将在第二个呼叫中完全在stack中处于同一位置,因此它仍然是具有第一个呼叫的值。但这只是机会,更改代码和行为会不明确地改变。C很有趣:)
为零,请在使用&amp; file拨打统计之前执行此操作:
memset(&file, 0, sizeof file);