【发布时间】:2018-03-10 21:12:48
【问题描述】:
我遇到了一个我似乎无法解决的非常奇怪的问题。
我正在尝试统计我的 C 程序目录中的文件,但有效文件返回 -1(该文件不存在)。问题是,这些文件是有效的,并且确实有一些数据。
另一个有趣的事情是默认目录。和 .. 返回 0。
下面是我的代码:
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <locale.h>
#include <langinfo.h>
#include <stdint.h>
#include <stdlib.h>
int main(int c, char *v[])
{
int len;
struct dirent *pDirent;
DIR *pDir;
char buffer[500] = {'\0'};
char *files[10000];
struct stat statbuf;
int i = 0;
int status;
if (c < 2)
{
printf("Usage: testprog <dirname>\n");
return 1;
}
pDir = opendir(v[1]);
if (pDir == NULL)
{
printf("Cannot open directory '%s'\n", v[1]);
return 1;
}
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/fstatat.html
while ((pDirent = readdir(pDir)) != NULL)
{
strcpy(buffer, (const char *)pDirent->d_name);
files[i] = malloc(strlen(buffer) + 1);
strcpy(files[i], buffer);
printf("buffer: %s \n", buffer);
if (stat(pDirent->d_name, &statbuf) == -1)
{
perror("stat");
exit(EXIT_FAILURE);
}
status = stat(pDirent->d_name, &statbuf);
printf("status: %d \n", status);
i++;
}
closedir(pDir);
return 0;
}
当我对目录中的文件运行 stat 命令时的输出如下:
buffer: test2
status: -1
buffer: .
status: 0
buffer: tset3
status: -1
buffer: ..
status: 0
buffer: test1
status: -1
有人可以指出我正确的方向吗?把我的头发拉在这里。
【问题讨论】:
-
pDirent->d_name是文件名,不是文件完整路径 -
您需要在调用
stat之后打印pDirent->d_name和strerror(errno)失败 - 你只是在调用 之后才这样做成功。我想不出一个很好的理由为什么连续两次使用相同参数的stat调用会产生不同的结果,但不知道pDirent->d_name和strerror(errno)是什么,我们只能在黑暗中猜测。 -
如果是这种情况,当您退出时如何打印
status: -1? -
谢谢,让-弗朗索瓦。这正是我所缺少的。
标签: c system-calls stat