cfileprocesspipefork

Reading file in child process in C


So basically, I'm trying to read a file and see if any of the lines matches with a given string in a child process that I've created. The answer is then transmitted to the parent process that prints it out. My problem is that my code only works if I input the last line in my txt file. Any other line is reported as not being present in the file.

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>

void Login()
{
char name[20];
int pfd[2];
pid_t pid;

pipe(pfd);

if((pid=fork()) == -1)
{
 exit(1);
}

if (pid==0)
{
 close(pfd[0]);
 FILE *fp = fopen("loginuser.txt", "r");
 printf("name:");
 scanf("%s", name);
 int ok = 0;
 if (fp!=NULL)
{
 char line[20];
 while (fgets(line,20,fp) !=NULL)
{
 if (strcmp(name,line)==0) ok = 1;
}
 fclose(fp);
}
 char s1[]="logged in!";
 char s2[]="Not found!";
 if(ok==1) write (pfd[1],s1,strlen(s1));
 else write(pfd[1],s2,strlen(s2));
 exit(0);
}
else
{ 
 close(pfd[1]);
 int n;
 char reada[20];
 n=read (pfd[0],reada,sizeof(reada));
 printf("%s",reada);
}
}

int main (int argc, char *argv[])
{
 Login();
 return 0;
}

loginuser.txt

aaabs
fas
ttt
aloo

Inputing anything other than aloo ,in this case, won't give the correct result. I also have two extra characters after the parent prints something. Any ideea what I've done wrong and why it's not working as intended ?


Solution

  • Fgets return the endtrail caracter in your line, meaning that you were actually comparing aaabs to aaabs\n, thus failing strcmp. If you do this instead :

          while (fgets(line,20,fp) !=NULL)
            {
              size_t i = strlen(line) - 1;
              if (line[i] == '\n')
                line[i] = '\0';
    
              if (strcmp(name,line)==0)ok = 1;
            }
    

    It'll remove each '\n' with a '\0' instead, cleaning your buffer from endlines.