我正在尝试弄清楚如何使用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()返回的信息吗?
发布于 2010-08-18 21:18:35
是的,buf在这里用作输出参数。结果存储在buf中,stat的返回值是一个错误代码,指示stat操作是成功还是失败。
之所以这样做是因为stat是一个为C设计的POSIX函数,它不支持带外错误报告机制,如异常。如果stat返回一个结构,那么它将无法指示错误。使用此参数外方法还允许调用者选择存储结果的位置,但这是次要功能。传递普通局部变量的地址是非常好的,就像您在这里所做的那样。
您可以像访问任何其他对象一样访问结构的字段。我想你至少熟悉对象表示法吧?例如,名为buf的stat结构中的st_dev字段由buf.st_dev访问。所以:
cout << buf.st_dev << endl;等。
发布于 2011-09-13 06:13:22
对于另一个项目,我提供了一个小函数,它可以做一些与你需要的事情相似的事情。看看sprintstatf吧。
下面是一个用法示例:
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include "sprintstatf.h"
int
main(int argc, char *argv[])
{
char *outbuf = (char *)malloc(2048 * sizeof(char));
struct stat stbuf;
char *fmt = \
"st_atime (decimal) = \"%a\"\n"
"st_atime (string) = \"%A\"\n"
"st_ctime (decimal) = \"%c\"\n"
"st_ctime (string) = \"%C\"\n"
"st_gid (decimal) = \"%g\"\n"
"st_gid (string) = \"%G\"\n"
"st_ino = \"%i\"\n"
"st_mtime (decimal) = \"%m\"\n"
"st_mtime (string) = \"%M\"\n"
"st_nlink = \"%n\"\n"
"st_mode (octal) = \"%p\"\n"
"st_mode (string) = \"%P\"\n"
"st_size = \"%s\"\n"
"st_uid = \"%u\"\n"
"st_uid = \"%U\"\n";
lstat(argv[1], &stbuf);
sprintstatf(outbuf, fmt, &stbuf);
printf("%s", outbuf);
free(outbuf);
exit(EXIT_SUCCESS);
}
/* EOF */发布于 2014-07-15 15:09:38
这个问题可能太老了,我把它贴出来作为参考
为了更好地理解stat()函数,下面的链接很好地解释了传递stat引用的原因以及更重要的错误处理
stat - get file status
https://stackoverflow.com/questions/3512434
复制相似问题