Search code examples
cstat

printing information from stat(2)


I have a file, and when I call stat(2) on it, I get:

  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: -

So I want to print out some information from this (and make it so that I can do the same for other files:

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

but I'm not sure how to actually obtain this information from the stat call. I know it contains things like st_uid that contains the user id, but I don't know how to actually grab that and then print it.

Edit:

I have found a way to access some of the information returned by stat(), but these two still give me problems:

int userName = fileStats.st_uid; returns 74112 instead of laz18

int groupName = fileStats.st_gid; returns 72216 instead of grp.csci.mentors

I need some way of accessing those, and the manual pages do not say how to do so.


Solution

  • To access user name and group name, you can use getpwuid(3) and 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);
    

    You have to include this headers too:

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