how to read a linux etc/passwd file and compare th

2020-07-27 05:52发布

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

标签: c
6条回答
Root(大扎)
3楼-- · 2020-07-27 06:45

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))
查看更多
神经病院院长
4楼-- · 2020-07-27 06:48

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 */
}
查看更多
时光不老,我们不散
5楼-- · 2020-07-27 06:50

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".

查看更多
SAY GOODBYE
6楼-- · 2020-07-27 06:50

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).

查看更多
家丑人穷心不美
7楼-- · 2020-07-27 06:51

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

查看更多
登录 后发表回答