首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用结构Stat()

使用结构Stat()
EN

Stack Overflow用户
提问于 2010-08-18 21:14:23
回答 6查看 84.1K关注 0票数 12

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

代码语言:javascript
复制
 #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()返回的信息吗?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-08-18 21:18:35

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

之所以这样做是因为stat是一个为C设计的POSIX函数,它不支持带外错误报告机制,如异常。如果stat返回一个结构,那么它将无法指示错误。使用此参数外方法还允许调用者选择存储结果的位置,但这是次要功能。传递普通局部变量的地址是非常好的,就像您在这里所做的那样。

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

代码语言:javascript
复制
cout << buf.st_dev << endl;

等。

票数 14
EN

Stack Overflow用户

发布于 2011-09-13 06:13:22

对于另一个项目,我提供了一个小函数,它可以做一些与你需要的事情相似的事情。看看sprintstatf吧。

下面是一个用法示例:

代码语言:javascript
复制
#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 */
票数 4
EN

Stack Overflow用户

发布于 2014-07-15 15:09:38

这个问题可能太老了,我把它贴出来作为参考

为了更好地理解stat()函数,下面的链接很好地解释了传递stat引用的原因以及更重要的错误处理

stat - get file status

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3512434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档