stat输出目录中文件的错误值

我正在尝试创建一个函数,它将获取目录中每个文件的输入目录路径(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); } 

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

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