gpt4 book ai didi

c++ - 统计()失败 : No such file or directory

转载 作者:太空宇宙 更新时间:2023-11-04 11:32:57 25 4
gpt4 key购买 nike

我想获取具有权限等的文件和文件夹列表,但对于每个项目,我都收到统计错误“没有这样的文件或目录”,并且列表仅包含项目“。”和“..”

代码:

list<string> res;
DIR *dirp;
dirp = opendir("/");
struct dirent *dp;
while ((dp = readdir(dirp)) != NULL){
stringstream ss;
struct stat fileStat;
if(stat(dp->d_name, &fileStat) < 0) {
std::cout << "stat() failed: " << std::strerror(errno) << "(" << dp->d_name << ")" << endl;
continue;
}


ss << ( (S_ISDIR(fileStat.st_mode)) ? "d" : "-" )
<< ( (fileStat.st_mode & S_IRUSR) ? "r" : "-")
<< ((fileStat.st_mode & S_IWUSR) ? "w" : "-")
<< ((fileStat.st_mode & S_IXUSR) ? "x" : "-")
<< ((fileStat.st_mode & S_IRGRP) ? "r" : "-")
<< ((fileStat.st_mode & S_IWGRP) ? "w" : "-")
<< ((fileStat.st_mode & S_IXGRP) ? "x" : "-")
<< ((fileStat.st_mode & S_IROTH) ? "r" : "-")
<< ((fileStat.st_mode & S_IWOTH) ? "w" : "-")
<< ((fileStat.st_mode & S_IXOTH) ? "x" : "-") << "\t"
<< fileStat.st_nlink << "\t"
<< fileStat.st_uid << "\t"
<< fileStat.st_gid << "\t"
<< fileStat.st_size << "\t";

char mbstr[100];
time_t t = (time_t)fileStat.st_mtim.tv_sec;
struct tm *tminfo = localtime ( &t );
strftime(mbstr, sizeof(mbstr), "%b %d %H:%M", tminfo );
ss << mbstr << "\t"
<< dp->d_name;
res.push_back(ss.str());
}

for( string s : res ){
cout << s << endl;
}

结果:

...
stat() failed: No such file or directory(usr)
stat() failed: No such file or directory(var)
stat() failed: No such file or directory(home)
stat() failed: No such file or directory(etc)
stat() failed: No such file or directory(bin)
drwxrwxr-x 9 1000 1000 4096 May 29 02:08 .
drwxrwxr-x 3 1000 1000 4096 Mar 16 22:36 ..

上面的例子是针对根“/”的,我已经尝试了很多目录,但错误不仅仅发生在当前目录“.”。

你能告诉我如何避免这个问题吗?谢谢!

最佳答案

您正在执行 stat()在目录名上,不在路径上。即你在“usr”而不是“/usr”上执行它

为避免您的问题,请确保在路径上调用 stat(您的 while 循环可能会构建)

关于c++ - 统计()失败 : No such file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23924049/

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