我想列出目录中的常规文件。但是,stat
对每个文件都失败。
DIR* dp = NULL;
struct dirent* entry = NULL;
dp = opendir(directory);
if (!dp) { log_err("Could not open directory"); return -1; }
while (entry = readdir(dp))
{
struct stat s;
char path[1024]; path[0] = 0;
strcat(path, directory);
strcat(path, entry->d_name);
int status = 0;
if (status = stat(path, &s))
{
if (S_ISREG(s.st_mode))
{
printf("%s\n", entry->d_name);
}
}
else
{
fprintf(stderr, "Can't stat: %s\n", strerror(errno));
}
}
closedir(dp);
输出
无法统计:资源暂时 不可用
无法统计:资源暂时 不可用
无法统计:资源暂时 不可用
(......很多次)
errno
设置为E_AGAIN
(11)。
现在,如果我打印出结果path
,它们确实是有效的文件和目录名称。该目录是可读的,我运行的用户确实有权这样做(这是我编写程序的目录)。
导致此问题的原因是什么?如何正确执行此操作?
答案 0 :(得分:3)
stat
以及许多其他系统调用在成功时返回0
,在失败时返回-1
。您错误地测试了stat
的返回值。
您的代码应为:
if (!stat(path, &s))
{
if (S_ISREG(s.st_mode))
{
printf("%s\n", entry->d_name);
}
}
else
{
fprintf(stderr, "Can't stat: %s\n", strerror(errno));
}
答案 1 :(得分:0)
你可能错过了一个分隔符。
strcat(path, directory);
strcat(path, "/"); //this is missing
strcat(path, entry->d_name);
分配字符串时,不要忘记考虑额外的'/'。