C:nftw()的奇怪行为
我有以下代码:C:nftw()的奇怪行为,c,size,mode,stat,C,Size,Mode,Stat,我有以下代码: #include <ftw.h> #include <stdio.h> #include <string.h> int nftw_stat(const char *path, const struct stat *stat, int flags, struct FTW *ftw) { if (strcmp(path, "/home/pf/.gvfs\0") == 0) { printf("n
#include <ftw.h>
#include <stdio.h>
#include <string.h>
int nftw_stat(const char *path, const struct stat *stat, int flags,
struct FTW *ftw)
{
if (strcmp(path, "/home/pf/.gvfs\0") == 0) {
printf("nftw()\n");
printf("mode = %d\n", stat->st_mode);
printf("size = %d\n", (int) stat->st_size);
}
return 0;
}
int main()
{
if (nftw("/home/pf", &nftw_stat, 1, FTW_PHYS)) {
perror("nftw");
return 2;
}
}
会发生什么?如果我将
stat()
与sudo
一起使用,则会出现权限被拒绝错误。这仅在权限为500(dr-x-----)的.gvfs
目录中发生。如果sudo
不能使用stat()
读取,为什么它可以使用nftw()
| 可能发生的情况是,stat在目录上失败了,但是您正在打印stat结构的值,这意味着您得到了垃圾。您需要检查typeflag的值,您在nftw_stat例程中称之为“flags”,以确保stat已成功设置stat结构
int nftw_stat(const char *path, const struct stat *stat, int typeflag,
struct FTW *ftw)
{
if (typeflag == FTW_NS) {
printf("stat failed on %s\n", path);
return 1;
}
if (strcmp(path, "/home/pf/.gvfs\0") == 0) {
printf("nftw()\n");
printf("mode = %d\n", stat->st_mode);
printf("size = %d\n", (int) stat->st_size);
}
return 0;
}
/home/pf目录上有哪些保护?它控制您看到的内容,而不是.gvfs目录本身上的权限掩码。顺便说一句,您不需要自己将
\\0
添加到C字符串中。很高兴了解@Hasturkun。谢谢你的提示!(我是C新手)我还想为注释添加FTW_DNR
到typeflag check+1,使用stat之类的工具,您应该尽可能多地捕捉错误,并阅读文档……也感谢FTW_DNR提示,@Hasturkun。这将是有用的。感谢@steabert给出了清晰的答案,我错过了typeflag参数的重要性。
mode = 16832 (S_IFDIR | S_IRWXU)
size = 4096
int nftw_stat(const char *path, const struct stat *stat, int typeflag,
struct FTW *ftw)
{
if (typeflag == FTW_NS) {
printf("stat failed on %s\n", path);
return 1;
}
if (strcmp(path, "/home/pf/.gvfs\0") == 0) {
printf("nftw()\n");
printf("mode = %d\n", stat->st_mode);
printf("size = %d\n", (int) stat->st_size);
}
return 0;
}