stat outputting the wrong values for files in a directory

后端 未结 1 1602
庸人自扰
庸人自扰 2021-01-22 13:54

I am trying to create a function that will take an inputted directory path (filrOrDir) and output info for each file in the directory: file name, size, and last access date. T

相关标签:
1条回答
  • 2021-01-22 14:02

    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.
    }
    
    0 讨论(0)
提交回复
热议问题