c - 从 stat(2) 打印信息

标签 c stat

我有一个文件,当我对其调用 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/

相关文章:

c - 使用 C 程序截取 Windows 桌面的屏幕截图。

c++ - 注入(inject)的 DLL 主循环导致进程崩溃

c - 如何将多个数据组合到一个变量中

python - 更好的 assertEqual() 为 os.stat(myfile).st_mode

c 程序,警告消息传递 ‘fstat’ 的参数 1 从指针生成整数而不进行强制转换

r - R 中的 ifelse 语句给出了错误的值

c - 如何在 C 中连接数组中的整数二进制值?

c - 如何等到窗口被映射和可见

macos - 苹果电脑 : Lack of --printf for stat

c - 如何在 C 代码中动态更改/伪造 'file size'