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!
With that command line
argv[2]
will beNULL
. So the linewill give segmentation fault.
You may want to do