Hi!
I'm trying to write a C function that searches a file for given keyword, and returns the first line containing the keyword. It works if I search for whole words, like:
theFile:
"Hello, I am a textfile.
I have two lines."
function searches theFile for "textfile" and returns: "Hello, I am a textfile".
But if it search for "xtfile", it can't find the line. What am I doing wrong?
Code:
char *readFileAndSearchForKeyWord(char *filename, char *keyWord) {
FILE * pFile;
long lSize;
long runTimes = 0;
char * streamLine;
pFile = fopen ( filename , "rb" );
if (pFile==NULL) {printf("ERROR: '%s' not found in configuration file '%s'\n", keyWord, filename); exit (1);}
// obtain the file size.
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file.
streamLine = (char*) malloc (lSize);
if (streamLine == NULL) exit (2);
//Search for keyWord
fgets (streamLine, lSize, pFile);
while (!strstr(streamLine, keyWord) && (lSize > runTimes)) {
fgets (streamLine, lSize, pFile);
runTimes++;
}
// terminate
fclose (pFile);
free (streamLine);
//Error?
if (runTimes == lSize)
{
printf("ERROR: '%s' not found in configuration file '%s'\n", keyWord, filename);
exit(1);
}
return streamLine;
}