gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:24:10 25 4
gpt4 key购买 nike

我实现了如下方法:

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 中。所以我实现了这个:

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。所以 Entity 的大小总是会被意外地赋值为 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() 之前打印路径名字符串,以验证您是否正确地添加了目录名称。

关于C++ stat(const char *d_name) 总是返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49878052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com