2

我正在尝试创建一个函数,该函数将采用输入的目录路径 (filrOrDir) 并为目录中的每个文件输出信息:文件名、大小和上次访问日期。该程序编译并打印所有内容。它打印正确的文件名,但是对于每个文件,大小和上次访问日期都是错误的。我想可能是因为我的变量声明在 while 循环中,但我移动了它们,仍然得到相同的结果。有人可以给我一个提示或提示我做错了什么吗?下面是我的代码:

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);

 }
4

1 回答 1

3

name = dir->d_name是目录中文件的名称fileOrDir,但是

stat(name, buffer);

尝试统计当前工作目录name中的文件。那会失败(除非碰巧是当前工作目录),因此不确定的内容。fileOrDirbuffer

您必须连接 stat 调用的目录和文件名。您还应该检查 stat 调用的返回值。例如:

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.
}
于 2014-03-09T16:36:24.610 回答