【问题标题】:stat() failed : No such file or directorystat() failed : 没有这样的文件或目录
【发布时间】:2014-05-29 00:41:15
【问题描述】:

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

代码:

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    ..

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

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

【问题讨论】:

    标签: c++ stat


    【解决方案1】:

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

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

    【讨论】:

    • 对,您必须将dp-&gt;d_name 附加到您提供给readdir() 的路径中——更一般地说,如果没有,您可能必须在它们之间插入一个'/' 字符已经有一个了。
    猜你喜欢
    • 2020-06-03
    • 2021-03-05
    • 2012-08-05
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 2017-01-24
    相关资源
    最近更新 更多