C++ stat(const char *d_name) 始终返回 -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
总是返回-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()
路径名字符串之前打印路径名字符串,以验证是否正确预置了目录名。
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- C++初学者:为什么我的编译器根据我的循环返回"name not found"?
- typeid.name 返回派生类类型之前的数字
- 返回别名标识符,而不是typeid(SOME_TYPE).name()中的类型
- getaddrinfo() 返回错误"The requested name is valid, but no data of the requested type was found."
- 在bison中,是否有一种方法可以返回令牌的Name而不是其类型
- 返回"does not name type"的模板化类
- 为什么name()函数返回的字符串是实现定义的
- 错误:"dependent name is not a type" 。当在类中使用 typedef 类型作为返回值时,带有模板
- 多次调用typeid(T).name()会返回相同的指针吗?