Find string that contains substring from redirected file, but keep getting Seg-fault?

603 Views Asked by At

The program requires me to find strings that contain substrings (specified in the command line argument) from a redirected file (filetoreadfrom.data). The file contains a list of words(strings). If the strings contain the substrings, then print the strings. The command line is as follows:

./program substring < filetoreadfrom.data

I keep getting "Segmentation-fault (Core dumped)" error message and I don't know why. At first I thought it's because of not malloc'ing my char array, but now that I've get rid of it by fixing the size of the char array using #define MAXchar 200, I really can't see what went wrong. Is it because of the memory space, my usage of fgets or strstr, or something wrong with the way I'm redirecting the file.

These are my codes:

    char line[MAXchar]; //MAXchar = 200
    int count=0;

    //check usage
    if ((strcmp("<", argv[2]))!=0){
            fprintf(stderr,"Usage: ./program substring\n");
            return 1;
    }

    //read lines from redirected file
    while (fgets(line,MAXchar,stdin)!=NULL){
            //find substring in each line
            //if substring is present in the line
            if (strstr(line,argv[1])!=NULL){
                    //print the line
                    fprintf(stdout, "%s\n", line);
                    count=1;
            }
    }
    //if none of the line contains the substring
    if (count==0){
            fprintf(stdout, "No match found\n");
    }

    return 0;

}

I hope you guys can shed some light in this. Thanks!

3

There are 3 best solutions below

0
On

With that command line argv[2] will be NULL. So the line

if ((strcmp("<", argv[2]))!=0){

will give segmentation fault.

You may want to do

if(argc < 2) {
    //show usage
}
1
On

it crashes when you check for argv[2]. there is no argv[2], as the < is a console/shell specific command which isn't passed through to your program. At the time you check argv[2] it's a NULL pointer, and you do not have permission to write/read there. that's why the segfault occurs.

e.g.

#include <stdio.h>
int main(int argc, char** argv)
{
  printf("%d\n", argc);
  return 0;
}

Output:

$ ./test < test.c
1
$
0
On

The < filetoreadfrom.data means use filetoreadfrom.data as stdin.

So you program only got two param : ./program substring

In you code, remove this part :

if ((strcmp("<", argv[2]))!=0){
            fprintf(stderr,"Usage: ./program substring\n");
            return 1;
    }

If you wonder user forget using < filetoreadfrom.data , may be you can pass the filetoreadfrom.data by ./program substring filetoreadfrom.data and open it ,

then use dup to copy the file description to STDIN_FILENO. or just read from it.

You can check theargc != 3to make sure user give a input file.