我正在尝试创建一个函数,它将采用输入的目录路径 (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
, but
stat(name, buffer);
尝试统计文件name
in the 当前工作目录。
那会失败(除非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.
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)