开发者

C: strange behavior with nftw()

I've this code:

#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;
    }
}

If I execute it normally, it returns the same way as stat() function:

mode = 16704 (S_IFDIR | S_IRUSR | S_IXUSR)
size = 0

But when I execute it with sudo, it returns this:

m开发者_JS百科ode = 16832 (S_IFDIR | S_IRWXU)
size = 4096

What happens? If I use stat() with sudo it give me the Permission denied error. This happens only with .gvfs directory, whose permissions are 500 (dr-x------). If sudo can't read with stat() , why it works with nftw()? :|


What's probably happening is that stat has failed on the directory, but you are printing the values of the stat structure regardless, meaning you get rubbish. You need to check the value of the typeflag, which you call "flags" in your nftw_stat routine to make sure that stat has successfully set the stat structure.

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜