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

时间:2014-05-24 14:55:39

标签: 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) {
        perror("stat"); 
    }

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

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

2 个答案:

答案 0 :(得分:3)

Alok SInghal的评论回答了我的问题。我不得不将_SC_GETPW_R_SIZE_MAX更改为更大的数字。

答案 1 :(得分:0)

有时候getpwuidgetgruid会失败,要解决这个问题,只需itoa st_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;
相关问题