Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中显示文件的所有者名称_C_Unix_Implementation_Ls - Fatal编程技术网

在C中显示文件的所有者名称

在C中显示文件的所有者名称,c,unix,implementation,ls,C,Unix,Implementation,Ls,我正在实现ls命令,现在正在执行-l选项。我对主人的名字有些疑问。它总是打印id而不是名称 以下是我的功能: void print_user_ID(char* filepath) { struct stat sb; struct passwd pwent; struct passwd *pwentp; char buf[_SC_GETPW_R_SIZE_MAX]; if(stat(filepath, &sb) == -1) {

我正在实现ls命令,现在正在执行-l选项。我对主人的名字有些疑问。它总是打印id而不是名称

以下是我的功能:

void print_user_ID(char* filepath) {
    struct stat sb;
    struct passwd pwent;  
    struct passwd *pwentp;
    char buf[_SC_GETPW_R_SIZE_MAX];

    if(stat(filepath, &sb) == -1) {
        perror("stat"); 
    }

    if (!getpwuid_r(sb.st_uid, &pwent, buf, sizeof(buf), &pwentp))  
        printf("%10s ", pwent.pw_name);  
    else  
        printf("%7d ", sb.st_uid);  
}

你知道我的错误在哪里吗?

阿洛克·辛格哈尔的评论回答了我的问题。我不得不将_SC_GETPW_R_SIZE_MAX更改为一个更大的数字。

有时
getpwuid
getgruid
失败,要解决这个问题,只需将
itoa
更改为
st\u uid
,它就会得到解决:D

像这样:

struct passwd   *pw;
struct group    *gr; 
if ((pw = getpwuid(st.st_uid)))
    (!arg->g) ? printf("%s", pw->pw_name) : NULL;
else
    (!arg->g) ? printf("%s", itoa(st.st_uid)) : NULL;

如果
getpwuid\u r()
\u SC\u GETPW\u R\u SIZE\u MAX
应该用于
sysconf()
函数中获取缓冲区大小。另外,只有当
stat
成功时,才应该调用
getpwuid\u r()
getpwuid\u r()
重新进入需要一个
malloc
ed内存,该内存可以
realloc
ed。将pwent更改为指针,然后为其分配内存,并将pwentp更改为指向pwent的地址。总之,它应该看起来像
getpwuid\r(sb.st\u uid,pwent,buf,sizeof(buf),&pwent)
其中
pwent
是一个带有分配内存的指针。您可能想接受自己的答案,所以现在这个问题得到了回答。
itoa()
是不可移植的。不仅如此,您发布的版本不是可重入的,而原始问题使用可重入的
getpwent\u r()
,可能是为了提供可重入的实现。原来的问题已经用
printf()
-
itoa()
正确地处理了,这完全是多余的。