I'm having trouble with a program that takes two command line arguments. The first argument is a string and the second argument is the name of a file. The program should then search the file (the file entered as the second argument) and print all the lines that contain the string entered in the first argument of the command line.
The file must be read line by line so I have to use fgets() plus I need the use of strstr() to find the string in the line of the text file. But I am not getting any results in my program. Here is what my code looks like right now:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *fp;
char buf[256];
if (argc != 2) {
printf("Supply two arguments: first a string, second a file name\n\n");
system("PAUSE");
exit(0);
}
else {
if ((fp = fopen(argv[1], "r")) == NULL) {
printf("Unable to open file %s\n\n", argv[1]);
system("PAUSE");
exit(0);
}
while (fgets(buf, 256, fp) != NULL && buf[0] != '\n') {
if (strstr(buf, argv[0])) {
fputs(buf, stdout);
}
}
}
system("PAUSE");
return 0;
}
The segment of the above code that is giving me problems is the
entire while loop (highlighted in BOLD) with the fgets() statement. Everything above that works OK. The problem is that I am not getting any results appearing on the screen from the search.
Any help, advice or suggestions would be greatly appreciated. I have included a sample "data.txt" file for reference.
Thanks.