gpt4 book ai didi

c - 从 stat(2) 打印信息

转载 作者:太空宇宙 更新时间:2023-11-04 04:17:41 24 4
gpt4 key购买 nike

我有一个文件,当我对其调用 stat(2) 时,我得到:

  File: 'testarg.txt'
Size: 8 Blocks: 1 IO Block: 121072 regular file
Device: 30h/48d Inode: 716627550 Links: 1
Access: (0644/-rw-r--r--) Uid: (74112/ laz18) Gid: (72216/grp.csci.mentors)
Access: 2018-04-29 14:56:51.380908597 -0700
Modify: 2018-04-29 14:37:51.230987592 -0700
Change: 2018-04-29 14:37:51.231987501 -0700
Birth: -

所以我想从中打印出一些信息(并制作它以便我可以对其他文件执行相同的操作:

file name: testarg.txt  
user name: laz18
group name: grp.csci.mentors
permissions: -rw-r--r--
links: 1
size: 8
modification time: 2018-4-29 14:37:51.230987592 -0700

但我不确定如何从 stat 调用中实际获取此信息。我知道它包含诸如包含用户 ID 的 st_uid 之类的内容,但我不知道如何实际获取并打印它。

编辑:

我找到了一种方法来访问 stat() 返回的一些信息,但这两个仍然给我带来问题:

int userName = fileStats.st_uid; 返回 74112 而不是 laz18

int groupName = fileStats.st_gid; 返回 72216 而不是 grp.csci.mentors

我需要一些方法来访问它们,手册页没有说明如何操作。

最佳答案

要访问用户名和组名,可以使用getpwuid(3)getgrgid(3)

struct passwd *pwd;
struct group *grp;
struct stat sb;

if (stat(argv[1], &sb) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}

pwd = getpwuid(sb.st_uid);
if (pwd == NULL) {
perror("getpwuid");
exit(EXIT_FAILURE);
}
printf("User %s\n", pwd->pw_name);

grp = getgrgid(sb.st_gid);
if (grp == NULL) {
perror("getgrgid");
exit(EXIT_FAILURE);
}
printf("group %s\n", grp->gr_name);

您还必须包含此 header :

#include <sys/types.h>
#include <grp.h>
#include <pwd.h>

关于c - 从 stat(2) 打印信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50091777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com