【问题标题】:Listing only regular files, problem with stat仅列出常规文件,stat 有问题
【发布时间】:2011-06-06 10:58:24
【问题描述】:

我想列出目录中的常规文件。但是,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,它们确实是有效的文件和目录名称。该目录是可读的,与我一起运行的用户确实有权这样做(这是我编写程序的目录)。

是什么导致了这个问题,我该如何正确地做到这一点?

【问题讨论】:

  • 您是否检查过指向该文件的路径中的所有目录都允许执行权限?

标签: c posix


【解决方案1】:

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));
}

【讨论】:

    【解决方案2】:

    您可能缺少分隔符。

    strcat(path, directory);
    strcat(path, "/"); //this is missing
    strcat(path, entry->d_name);
    

    在分配字符串时不要忘记考虑额外的“/”。

    【讨论】:

      猜你喜欢
      • 2010-12-10
      • 1970-01-01
      • 2019-05-02
      • 2013-08-09
      • 2020-01-11
      • 2011-12-19
      • 1970-01-01
      • 2011-03-26
      相关资源
      最近更新 更多