【问题标题】:stat() is returning that existing files don't exist (C) [duplicate]stat()返回现有文件不存在(C)[重复]
【发布时间】: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-&gt;d_name 是文件名,不是文件完整路径
  • 您需要在调用stat 之后打印pDirent-&gt;d_namestrerror(errno) 失败 - 你只是在调用 之后才这样做成功。我想不出一个很好的理由为什么连续两次使用相同参数的stat 调用会产生不同的结果,但不知道pDirent-&gt;d_namestrerror(errno) 是什么,我们只能在黑暗中猜测。
  • 如果是这种情况,当您退出时如何打印status: -1
  • 谢谢,让-弗朗索瓦。这正是我所缺少的。

标签: c system-calls stat


【解决方案1】:

您需要将目录名称与“/”和dentry名称连接起来并将其传递给stat,或者您需要使用目录的fd和dentry名称调用fstatat(或者您需要在您正在阅读的目录,以便每个目录名称同时是正确的相对名称)。

【讨论】:

    猜你喜欢
    • 2015-06-02
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 2012-05-03
    • 1970-01-01
    相关资源
    最近更新 更多