我试图弄清楚如何使用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;
...
}
Run Code Online (Sandbox Code Playgroud)
我对如何做到这一点感到很困惑.为什么&buf参数是stat?我不关心将这些信息存储在内存中,我只需要在我的c ++程序中输出字段.如何访问结构中包含的信息?buf实际上应该包含stat()返回的信息吗?
Tyl*_*nry 12
是的,buf这里用作参数.结果存储在其中buf,返回值stat是一个错误代码,指示stat操作是成功还是失败.
它是以这种方式完成的,因为它是stat为C设计的POSIX函数,它不支持异常等带外错误报告机制.如果stat 返回一个结构,那么就无法指出错误.使用此out-parameter方法还允许调用者选择他们想要存储结果的位置,但这是次要功能.传递正常局部变量的地址完全没问题,就像你在这里做的那样.
您可以像访问任何其他对象一样访问结构的字段.我认为你至少熟悉对象符号?例如,被调用st_dev的statstruct中的字段buf被访问buf.st_dev.所以:
cout << buf.st_dev << endl;
Run Code Online (Sandbox Code Playgroud)
等等