C++ stat(const char *d_name) 总是 returns -1

C++ stat(const char *d_name) always returns -1

我实现了如下方法:

long getSize(const char *d_name)
{
    struct stat buff {};

    // stat(const char* var) always returns -1
    int exists = stat(d_name, &buff);

    long totalSize = 0;

    // So totalSize never increases
    if (exists > -1)
        totalSize += buff.st_size;

    return totalSize;
} 

我也有一个结构:

struct Entity
{
    string name;
    string type;
    long size;
    string created_at;
    string modofied_at; // equivalence to "modified" phrase
    bool isHidden;
};

我想遍历特定路径中的文件并将它们的数据(大小、名称等)定位到包含每个实体(文件或目录)结构的向量中。所以我实现了这个:

vector<Entity> getEntities(const char *path)
{
    vector<Entity> entities;

    DIR *dir;
    struct dirent *ent;

    /** if path exists **/
    if ((dir = opendir(path)) == nullptr)
    {
        /* could not open directory */
        perror("path_invalid");
        exit(1);
    }

    /** loop over entities till encounters nullptr **/
    while ((ent = readdir(dir)) != nullptr)
    {
        Entity entity;

        entity.name = ent->d_name;

        // This member is always 0
        entity.size = this->getSize(ent->d_name);

        entity.isHidden = this->isHidden(ent->d_name);
        entities.push_back(entity);
    }

    closedir(dir);
    return entities;
} 

问题是 stat 总是 returns -1。所以Entity的size总会意外的赋值为0.

if ((dir = opendir(path)) == nullptr)

假设您在这里打开了“/etc”目录。这里,path 将是“/etc”。

代码然后继续遍历目录。假设它找到了 passwd 文件;也就是说,您现在将使用“/etc/passwd”。

entity.size = this->getSize(ent->d_name);

d_name 将在此处 "passwd"。这是该目录中该文件的名称。然后,当你开始做生意时,你的代码会这样做:

int exists = stat(d_name, &buff);

这当然会失败并且 return -1。这将尝试 stat() 名称为 "passwd".

的文件

当然,不存在这样的文件。该文件是“/etc/passwd”。

您需要在文件名前加上目录名,以形成完整的路径名。出于调试目的,请确保在 stat() 之前打印路径名字符串,以验证您是否正确地添加了目录名称。