Reputation: 1
Check for a word in a text file line by line and when you found it,print the whole line,the program receives as command line argumets the text file and the word you are searching for. Here is what I've tried to do so far,but I have segmentation fault and I don't really know what I'm supposed to do.
int main(int argc, char const *argv[])
{
FILE *file;
if(argc!=3)
{
printf("error 1");
exit(1);
}
if((file=fopen(argv[1],"r"))==NULL)
{
printf("Error");
exit(1);
}
char line[100];
char *p;
while(!feof(file))
{
fgets(line,sizeof(line),file);
p=strtok(line," ");
while(strcmp(p,argv[2])!=0)
p=strtok(NULL," ");
if(strcmp(p,argv[2])==0)
{
printf("%s",line);
}
}
fclose(file);
return 0;
}
Upvotes: 0
Views: 179
Reputation: 75062
You are doing strcmp(p,argv[2])
without checking p
is NULL
. You should check that.
Also your usage of while(!feof(file))
is wrong. You should check if readings succeeded before using what are "read".
Fixed code:
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
FILE *file;
if(argc!=3)
{
printf("error 1");
exit(1);
}
if((file=fopen(argv[1],"r"))==NULL)
{
printf("Error");
exit(1);
}
char line[100];
char *p;
while(fgets(line,sizeof(line),file)) /* check if reading succeeded */
{
p=strtok(line," ");
while(p!=NULL && strcmp(p,argv[2])!=0) /* check if p is not NULL */
{
p=strtok(NULL," ");
}
if(p!=NULL && strcmp(p,argv[2])==0) /* check if p is not NULL */
{
printf("%s",line);
}
}
fclose(file);
return 0;
}
Upvotes: 1