【问题标题】:stat outputting the wrong values for files in a directorystat 为目录中的文件输出错误的值
【发布时间】:2014-04-12 15:27:04
【问题描述】:

我正在尝试创建一个函数,该函数将采用输入的目录路径 (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);

 }

【问题讨论】:

    标签: c stat dirent.h


    【解决方案1】:

    name = dir->d_namefileOrDir目录下的文件名,但是

    stat(name, buffer);
    

    尝试统计 当前工作目录中的文件 name。 失败(除非fileOrDir 恰好是当前工作目录), 因此buffer 的内容是不确定的。

    您必须为 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.
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-05
      • 2012-08-05
      • 1970-01-01
      • 2019-02-23
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      相关资源
      最近更新 更多