所以我从struct dirent派生了一个类。这是我的派生类标题的样子: #ifndef Direntry_hpp #define Direntry_hpp
#include <dirent.h>
#include <iostream>
using namespace std;
class Direntry : public dirent{
private:
public:
void print(ostream&);
char* name(){ return d_name; }
ino_t inode(){ return d_ino; }
unsigned int type(){ return d_type; }
};
#endif /* Direntry_hpp */
所以在我的代码中,我尝试使用readdir()和我上面类的一个类对象来存储它。所以readdir()返回struct dirent *。我已尝试过所有内容,但我无法使用我的类对象来存储readdir()的结果。
for(;;){
//I want to say Direntry *dirEntry but it doesn't work when I try to store the result of readdir().
struct dirent* dirEntry;
if((dirEntry = readdir(dir)) == nullptr) break;
if(params.vFlag && dirEntry->d_type != DT_REG){
cout << setw(12) << dirEntry->d_ino << left << dirEntry->d_name << endl;
} else if(dirEntry->d_type == DT_REG){
cout << setw(12) << dirEntry->d_ino << left << dirEntry->d_name << endl;
Stats stat; //This class is derived from stat in the <sys/stat.h> library and it works.
if(lstat(path, &stat)) fatal("lstat error");
}
}
因此,Stat类派生自并且它可以工作,但由于某种原因,struct dirent并不像我预期的那样工作。我做错了什么,或者我想做一些不应该做的事情?
修改
Direntry* dirEntry;
if((dirEntry = readdir(dir)) == nullptr) break;
上面的代码在编译时产生错误,说明:
分配到&#39; Direntry *&#39;来自不兼容的类型&#struct; struct dirent *&#39;
答案 0 :(得分:0)
DIR* dir = opendir(path);
for(;;){
Direntry* dirEntry;
if((dirEntry = (Direntry*)readdir(dir)) == nullptr) break;
...
}
所以我发现你可以将struct dirent *的readdir()的返回值转换为Direntry *,它是从struct dirent派生的类