stat outputting the wrong values for files in a directory

允我心安 提交于 2019-12-02 01:41:53

name = dir->d_name is the name of the file inside the directory fileOrDir, but

stat(name, buffer);

tries to stat the file name in the current working directory. That fails (unless fileOrDir happens to be the current working directory), and therefore the contents of buffer is undetermined.

You have to concatenate the directory and the file name for the stat call. You should also check the return value of the stat call. For example:

char fullpath[MAXPATHLEN];
snprintf(fullpath, sizeof(fullpath), "%s/%s", fileOrDir, name);
if (stat(fullpath, buffer) == -1) {
    printf(stderr, "stat failed: %s\n", strerror(errno));
} else {
    // print access time etc.
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!