I am having trouble with a project for a computer science class in c. I am calling a function I created that reads from a file, stores it in a char array, then sends this to another function I created so that I may print the result from a single line that contains a particular string called string. All seems to work except for one thing. If I want the whole document printed, I send in NULL in place of string. However, after this is done, the program also prints out the results of the last time the function was called without a NULL in place of string. I can't figure out why though. Any help is greatly appreciated. Here is the appropriate code.
/*getText.c*/
#include<stdio.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
#include"getText1.h"
void getFileText(char *fileName, char *keyWord)
{
FILE *file = fopen(fileName, "r");
char *answer = (char*)malloc(sizeof(char)*MAX_FILE);
if(file != NULL)
{
fread(answer, sizeof(char), MAX_FILE, file);
parseText(keyWord, answer);
}
else
{
perror("Error in getText.c, fopen:");
exit(-1);
}
fclose(file);
free(answer);
}
void parseText(char *string, char *text)
{
char buff[MAX_FILE];
char * ptr;
int a = 0;
strcpy(buff, text);
ptr = strtok(buff, "\n");
if(string != NULL)
{
while(ptr != NULL && a == 0)
{
if(strstr(ptr, string) != NULL)
{
printf("test1 ");
printf("%s\n", ptr);
printf(" test2\n");
a = 1;
}
ptr = strtok(NULL, "\n");
}
}
else
{
printf(text);
}
}
/*main*/
#include<stdio.h>
#include<string.h>
#include"getText1.h"
#include"fileName.h"
int main ()
{
getFileText("/proc/diskstats", "sda");
printf("Uptime ");
getFileText(UPTIME, NULL);
getFileText(TIME, TIME_KEYWORD);
printf("Kernel Version ");
getFileText(KERNEL, NULL);
return 0;
}
And the problem I am getting is that the first call to getFileText() works fine, and prints out the appropriate line. However, when I call it again for UPTIME with string being NULL, it prints out the entire the /proc/uptime (or UPTIME) and then the entire /proc/diskstats and does the same thing when I call it for KERNEL, but it works frine when I call it for TIME.