I think there are 2 potential problems
Problem 1 is the stack. The stack is a (relatively) small bit of memory used per thread to keep track of function automatically scoped variables, values in and out and such. It is not meant for large amounts of data. It is quite possible that your line
buffer is just too large for the stack!
If you want a buffer that large it is best to use malloc()
to allocate on the heap. The heap is large and if the allocation fails you can detect it and handle it appropriately.
Problem 2 is not checking the value of fp
. fopen()
may return NULL
if it fails to open the file. If this is the case and you pass fp
to fgets()
you'll get a seg fault.
When I addressed these two problems on my machine, your program worked...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSIZE 99999
int main()
{
char *line = malloc(BUFSIZE);
FILE *fp = fopen("file.txt", "r");
if(!line || !fp) {
printf("OOPS");
free(line);
return 1;
}
while (fgets(line, BUFSIZE, fp) != NULL)
{
if (strstr(line, "word") != NULL)
{
printf("%s", line);
}
}
fclose(fp);
free(line);
return 0;
}
Note fgets()
reads at most one less than the size parameter and will append a null terminator for you.