我正在尝试查找某个路径是否为目录。
我正在使用 <sys/stat.h>
中的统计函数使用以下代码:
int isDir(char *path){
printf("%s\n", path);
struct stat file;
stat(path, &file);
printf("%i\n", file.st_mode);
int x;
x = S_ISDIR(file.st_mode);
return x;
}
// I tried this function with the following code.
printf("%i\n", isDir("/home/aladdin"));
printf("%i\n", isDir("/home/aladdn"));
我在 PC 上的用户名是 aladdin
所以,第一个应该有效并且等于1
, 第二个应该打印 0
,因为没有名为 aladdn
的用户.
所以运行前面的代码给出
/home/aladdin
16832
1
/home/aladdn
16832
1
知道哪里出了问题吗?
最佳答案
您必须检查统计返回码。如果 stat 失败,它不会修改你的文件结构内容,在这种情况下它 IS_DIR 似乎返回 true。
所以,代替你当前的行 stat(path, &file);
,有一行:
if (stat(path, &file) == -1) 返回 0;
...当然,您可能应该以某种方式报告错误,具体取决于您的要求,但这个简单的更改将修复您的功能。
至于为什么你会得到相同的结果,我认为 C 会保留未初始化的结构,除非你明确地初始化它们,并且使用这种用法,结构将在第二次调用时位于堆栈中的相同位置,所以它仍然具有第一次调用的值。但这只是偶然,更改代码和行为变化不可预测。 C 这样很有趣:)
要将 buf 清零,请在使用 &file 调用 stat 之前执行此操作:
memset(&file, 0, sizeof file);
关于c - stat 函数在多次调用时不会改变它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12999597/