stat outputting the wrong values for files in a directory

我是研究僧i 提交于 2019-12-02 03:06:45

问题


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. The program compiles and prints everything. It prints the right file names but, for each file, the size and last access date are wrong. I thought maybe it was because of my variable declarations being in the while loop but I moved them around and still go the same results. Can somebody please give me a hint or a tip on what I am doing wrong? Below is my code:

void dirInfo(char *fileOrDir)
{
  DIR *d;
  struct dirent *dir;
  d = opendir(fileOrDir);

  while((dir = readdir(d)) !=NULL)
  {
    struct stat *buffer = (struct stat *)malloc(sizeof(struct stat));
    char accessString[256];
    char *name = (char *)malloc(sizeof(char));
    struct tm *tmAccess;
    int size = 0;

    name = dir->d_name;

    stat(name, buffer);
    printf("%s     ", name);


    size = buffer->st_size;
    printf("%d bytes     ", size);

    tmAccess = localtime(&buffer->st_atime);
    strftime(accessString, sizeof(accessString), "%a %B %d %H:%M:%S %Y", tmAccess);
    printf("%s\n", accessString);

    printf("\n");
    free(buffer);

  }

  closedir(d);

 }

回答1:


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.
}


来源:https://stackoverflow.com/questions/22284709/stat-outputting-the-wrong-values-for-files-in-a-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!