开发者

how to compare user given input(string) to /etc/passwd file in ubuntu in c

开发者 https://www.devze.com 2023-01-13 00:36 出处:网络
I开发者_C百科 want to compare user given input i.e a username to the already stored usernames in /etc/passwd file in ubuntu. I am trying it in C. any help please #include <pwd.h>

I开发者_C百科 want to compare user given input i.e a username to the already stored usernames in /etc/passwd file in ubuntu. I am trying it in C. any help please


#include <pwd.h>
...

struct passwd *e = getpwnam(userName);
if(e == NULL) {
   //user not found
} else {
  //found the user
}

See docs here and here

(If you actually want to authenticate the user as well, there's more work needed though )


This code prints all the usernames from /etc/passwd.

#include <stdio.h>

int main()
{  
        char buffer[128];
        char* username;
        FILE* passwdFile;

        passwdFile = fopen("/etc/passwd", "r");
        while (fgets(buffer, 128, passwdFile) != NULL)
        {
                username = strtok(buffer, ":");
                printf("username: %s\n", username);
        }
        fclose(passwdFile);
        return 0;
}

Modify to compare username to your input.

0

精彩评论

暂无评论...
验证码 换一张
取 消