suhel
suhel

Reputation: 753

how to read a linux etc/passwd file and compare the user input name for authentication in C

This is the program i have written can anyone tell what is wrong with it, because whatever input i give, it shows valid user.

#include<stdio.h>
#include<string.h>
#define max_size 20
void main()
{
 File *Fptr;
 char username[max_size];
 char line[20];
 if((fptr=fopen("/etc/passwd","r"))==NULL)
 { 
   printf("cannot open file");
 }
 else
  {
      fptr=fopen("/etc/passwd","r");
      fputs("enter the username",stdout);
      fflush(stdout);
      fgets(username,sizeof username,stdin);
      while((fgets(line,sizeof(line),fptr))!=NULL)
      { 
          if(strcmp(line,username))
          {
             printf("%s valid user",username);
             break; 
          }
          else
            {
              printf("%s not valid user",username);
            }    
      } 
   fclose(fptr);
  }
}

Upvotes: 1

Views: 5986

Answers (6)

bstpierre
bstpierre

Reputation: 31226

Aside from the fact that your strcmp test condition is wrong as others have already pointed out, lines in the passwd file contain more than just the username. You could use strstr to see if the name is present in a particular line.

if(strstr(line, username) == line)
{
    /* valid user */
}

Upvotes: 0

Hasturkun
Hasturkun

Reputation: 36412

Instead of trying to parse /etc/passwd manually, you might want to use getpwnam instead.

Upvotes: 3

Chowlett
Chowlett

Reputation: 46677

strcmp returns 0 (which is false) if the two strings are exactly equivalent, or a non-zero number (which is true) if the strings differ at all.

So firstly, you appear to have your if-test the wrong way around. Secondly, you need to test just the leading n characters, where n is the length of the username. Off the top of my head, I suggest you try replacing your if-test with:

if (!strncmp(line, username, strlen(username))

Upvotes: 2

Tyler McHenry
Tyler McHenry

Reputation: 76710

strcmp is a three-way comparator. It tells you if the strings are equal or if the first string is lexicographically less or greater than second.

Because of this, its results are a bit unintuitive when used as booelan values. It returns 0 when the strings match, which evaluates to false in an if statement. It returns nonzero values, usually -1 or 1, (all of which evaluate to true) when the strings are different.

If you want to test if two strings are the same, you should change

if(strcmp(line,username))

to

if(strcmp(line,username) == 0)

Also take note of Starkey's answer about the extra contents of lines in /etc/passwd. If you make only the change above, your program will always return "not a valid user".

Upvotes: 3

Starkey
Starkey

Reputation: 9781

strcmp compares the whole line in the passwd file with what you have entered. The passwd file contains more than just the user name on each line (look at a passwd file to see what I'm talking about).

Upvotes: 1

Related Questions