简体   繁体   中英

Show owner name of a file in C

I'm implementing the ls command and I'm doing the -l option right now. I have some issues with the owner's name. It always print's the id instead of name.

Here is my function:

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);  
}

Do you have any idea where is my mistake?

The comment of Alok SInghal answers my question. I had to change _SC_GETPW_R_SIZE_MAX to a bigger number.

Sometimes getpwuid or getgruid fails, to fix that just do a itoa to st_uid and it will be fixed :D

Like this:

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;

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