0

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;
}
pppppp123
  • 1
  • 3
  • 3
    By the way, your usage of `while(!feof(file))` looks [wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – MikeCAT Jul 27 '21 at 12:48
  • 1
    make a copy of the line string before using `strtok`, which is destructive. Then you have the original line to report. – Weather Vane Jul 27 '21 at 12:50
  • 2
    Welcome to SO. First step would be to run your program in a debugger. Step through your code and watch if the variables contain expected values. You can also just run it in debugger and when the segfault happens inspect where it happened and what data was used. – Gerhardh Jul 27 '21 at 12:50
  • 1
    `while(strcmp(p,argv[2])!=0)` you know that `strtok` might return `NULL`, do you? – Gerhardh Jul 27 '21 at 12:51

1 Answers1

1

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;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70