stat()失败:没有这样的文件或目录

时间:2014-05-29 00:41:15

标签: c++ stat

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

代码:

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

以上示例适用于root&#34; /&#34;我已经尝试了很多目录但是只有当前目录才会出现错误&#34;。&#34;。

请告诉我如何避免这个问题?谢谢!

1 个答案:

答案 0 :(得分:1)

您正在目录名称上执行stat()不在路径上。 即你正在&#34; usr&#34;而不是&#34; / usr&#34;

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