简体   繁体   中英

C get owner and group of file/directory

I getting the error segmentation fault when I run my C program. This is my code sample to get the owner and the group of the file/directory :

    struct stat sb;
    char outstr[200];

    stat(file_or_dir_name, &sb);

    struct passwd *pw = getpwuid(sb.st_uid);
    struct group  *gr = getgrgid(sb.st_gid);

    printf("%s %s\n", pw->pw_name, gr->gr_name);

The code run through the directory multiple times, but then at one file I get an error at pw->pw_name . Is it possible that some files/directories have no owner or why could I get the "Segmentation fault" ?

UPDATE: After error checking I got the following results (like -ls in find):

119 0 ---xrwxr-- 91 - daemon 9007206 Apr 29 00:03 ./Test/test.txt

119 0 ---xrwxr-- 91 - daemon 9007206 Apr 29 00:03 ./Test/Test2

119 0 ---xrwxr-- 91 - daemon 9007206 Apr 29 00:03 ./Test/Test2/test2.txt

Whats wrong with this files/directories?

Check the return values for getpwuid and getgrgid. You are not doing basic error checking on the stat function either. Error check as much as you can. Assume nothing works.

From your ls output, notice that you have daemon 9007206 for owner/group.

This means that the uid was found [by getpwuid ] in /etc/passwd [or equiv].

But the group was not found [by getgrgid --which would return NULL ] in /etc/group [or equiv].

ls handled this and printed the numeric value for gid .

Side note: 9007206 seems a little screwy to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM