本文介绍了使用Struct Stat()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何使用stat()捕获有关文件的信息.我需要的是能够打印关于文件的信息的多个字段.所以..

I'm trying to figure out how exactly to use stat() to capture information about a file. What I need is to be able to print several fields of information about a file. So..

 #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()返回的信息?

I'm thoroughly confused about how to do this. Why is &buf a parameter to stat? I don't care about storing this information in memory, I just need the outputted fields within my c++ program. How do I access the information contained in the struct? Is buf actually supposed to contain the returned information from stat()?

推荐答案

是的,buf在这里用作输出参数.结果存储在buf中,并且stat的返回值是一个错误代码,指示stat操作是成功还是失败.

Yes, buf is being used here as an out-parameter. The results are stored in buf and the return value of stat is an error code indicating if the stat operation succeeded or failed.

之所以这样做是因为stat是专为C设计的POSIX函数,它不支持异常之类的带外错误报告机制.如果stat 返回了一个结构,那么它将无法指示错误.使用此超参数方法还可以使调用者选择他们想要将结果存储在何处,但这是次要功能.就像您在此处所做的那样,传递普通局部变量的地址是完全可以的.

It is done this way because stat is a POSIX function, designed for C, which does not support out-of-band error reporting mechanisms like exceptions. If stat returned a struct, then it would have no way to indicate errors. Using this out-parameter method also allows the caller to choose where they want to store the results, but that's a secondary feature. It's perfectly fine to pass the address of a normal local variable, just like you have done here.

您可以像访问其他任何对象一样访问结构的字段.我想您至少熟悉对象表示法吗?例如. buf.st_dev在名为bufstat结构中的st_dev字段被buf.st_dev访问.所以:

You access the fields of a struct like you would any other object. I presume you are at least familar with object notation? E.g. the st_dev field within the stat struct called buf is accessed by buf.st_dev. So:

cout << buf.st_dev << endl;

这篇关于使用Struct Stat()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 02:55