Search code examples
clinuxowner

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?


Solution

  • 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.