繁体   English   中英

C获取文件和目录的所有者和组

[英]C get owner and group of file/directory

运行C程序时出现错误分段错误。 这是我的代码示例,用于获取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);

该代码在目录中多次运行,但是在一个文件中, pw->pw_name出现错误。 某些files/directories是否可能没有所有者,或者为什么我会出现"Segmentation fault"

更新:错误检查后,我得到以下结果(如-ls in find):

119 0 --- xrwxr-- 91-守护程序9007206 Apr 29 00:03 ./Test/test.txt

119 0 --- xrwxr-- 91-守护程序9007206 Apr 29 00:03 ./Test/Test2

119 0 --- xrwxr-- 91-守护程序9007206 Apr 29 00:03 ./Test/Test2/test2.txt

这个文件/目录怎么了?

检查getpwuid和getgrgid的返回值。 您也没有对stat函数执行基本的错误检查。 尽可能多地进行错误检查。 假设没有任何效果。

ls输出中,请注意您拥有所有者/组的daemon 9007206

这意味着uid是[通过getpwuid ]在/etc/passwd [或equiv]中找到的。

但该集团找到[由getgrgid ,可呈现将返回NULL ]在/etc/group [或当量。

ls处理了此问题并打印了gid的数值。

旁注: 9007206对我来说似乎有点9007206

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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