我想弄清楚如何使用stat()捕獲有關文件的信息。我需要的是能夠打印關於文件的幾個信息字段。所以..使用Struct Stat()
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
int main() {
struct stat buf;
stat("file",&buf);
...
cout << st_dev << endl;
cout << st_ino << endl;
cout << st_mode << endl;
cout << st_nlink << endl;
cout << st_uid << endl;
cout << st_gid << endl;
cout << st_rdev << endl;
cout << st_size << endl;
cout << st_blksize << endl;
cout << st_blocks << endl;
cout << st_atime << endl;
cout << st_mtime << endl;
cout << st_ctime << endl;
...
}
我對如何做到這一點感到非常困惑。爲什麼& buf參數stat?我不在乎將這些信息存儲在內存中,我只需要在我的C++程序中輸出的字段。我如何訪問結構中包含的信息? buf是否應該包含stat()返回的信息?
我看解釋好,三江源所有答案。他們相當有幫助。有誰知道如何使用stdin,stdout或stderr作爲統計工作的參數嗎?這些是流而不是文件,那麼stat如何用數據填充結構? – 2010-08-18 13:33:39
使用'fstat',它將文件描述符作爲其第一個參數而不是路徑。 – 2010-08-18 13:41:10
通常我會這樣做,但環境有點人爲,因爲這是我寫的建築模擬器的操作系統部分。所以當一個文件被系統調用打開時,我有自己的向量來充當文件描述符表。打開文件時,是否有一種很好的方法來捕獲計算機上實際的文件描述符?如果是這樣的話,我會使用fstat,因爲在流統計和文件統計之間不需要翻譯。 – 2010-08-18 13:48:24