Hello,

I have written a program in c which searches for a string in a text file. The program works, however I get a 'segmentation fault' error after the program terminates. I believe I have tracked the problem down to the while loop inside function Read(). Any help is much appreciated.

Thanks,

--------------------------------------------------------------------------
Code:
#include <stdio.h>
#include <string.h>

/* Declare static maximum array size */
const int MAX_INPUT_SIZE = 60000;

/************************************************** *************
Task: Read text file and search for string
Implementation: Asks the user to input a string they would like
to search for, and loads each string array 'index' with a line
from the file using strstr(). The program searches for the user's
string as each line is read. The program then notifies the user
of the results.
************************************************** **************/
void Read(FILE* file)
{
char* _string;

char token[MAX_INPUT_SIZE];

int count = 0;

printf("\nString to search for: ");

fflush(stdout);

fgets(token, 10, stdin);

if (token[strlen(token) - 1] == '\n')
{
token[strlen(token) - 1] = '\0';

} // End if

while (fgets(_string, 1024, file) != NULL)
{
if (strstr(_string, token) != NULL)

count++;

_string = _string + 1;

} /* End while */

if (count != 0)

printf("\nSuccess!!!\n\nString found: %d times\n\n", count);

else

printf("\nString not found\n\n");

} /* End read */

/************************************************** *************
Task: Program entry point main()
Implementation: main asks the user to input a file for reading.
Afterwards it calls function Read() to search for a string.
************************************************** **************/
int main(int argc, char *argv[])
{
FILE * doc;

char filename[50];

printf("\nFile to open: ");

fgets(filename, 50000, stdin);

/* Ensures the file name has no return characters */
if (filename[strlen(filename) - 1] == '\n')
{
filename[strlen(filename) - 1] = '\0';

} // End if

/* Open file */
doc = fopen(filename, "r");

if (!doc)
{
printf("\nFile not found!\n");

exit(1);

} // End if

/* With file opened, call function to read file */
Read(doc);

fclose(doc);

return 0;

} /* end main */

Last edited by shabbir; 4Dec2006 at 10:58.. Reason: Code formating.