所以我從struct dirent派生了一個類。這是我的派生類的頭看起來像: 的#ifndef Direntry_hpp 的#define Direntry_hpp如何從struct dirent派生類並使用它來存儲readdir()的結果?
#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類來源於和它的作品,但由於某種原因,結構的dirent不工作,我期待它的方式。我做錯了什麼或者我想做什麼不應該做的事情?
編輯:
Direntry* dirEntry;
if((dirEntry = readdir(dir)) == nullptr) break;
上面代碼在編譯時錯誤,指出:
分配到 'Direntry *' 從不兼容的類型 '結構的dirent *'
「某些原因struct dirent不能按我預期的方式工作」 - >它是如何失敗的 - 顯示輸出?預期什麼? – chux
希望此代碼僅用於學習,不會用於其他地方... – 0x0C4
是的,這純粹是爲了學習UNIX文件系統 –