C++ stat(const char *d_name) 始终返回 -1

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

本文关键字:name 返回 stat const char C++      更新时间:2023-10-16

我实现了如下方法:

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总是返回-1 .因此,实体的大小将始终意外地分配给 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);

当然,这将失败并返回 -1。这会尝试stat()名称为"passwd"的文件。

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

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