stat outputting the wrong values for files in a di

2019-02-26 11:17发布

问题:

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


标签: c stat dirent.h