I am trying to read a line from a file and return it and I want to call this function iteratively as long as I reach EOF or the last line. This is the code.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define BUFF 100000
int grep_stream(FILE* fpntr, char* string, char* filepathname);
char* get_next_line(FILE* fpntr);
int main()
{
FILE* fp;
fp = fopen("movies.txt", "r");
char* filename = "test";
char* searchString = "the";
grep_stream(fp, searchString, filename);
return 0;
}
int grep_stream(FILE* fpntr, char* string, char* filepathname)
{
char* tmp = get_next_line(fpntr);
char* ret;
while(tmp != NULL)
{
ret = strstr(tmp, string);
printf("%s\n", ret);
tmp = get_next_line(fpntr);
}
return 0;
}
char* get_next_line(FILE* fpntr)
{
char buff[BUFF];
int index = 0;
int ch = fgetc(fpntr);
while(ch != '\n' && ch != EOF)
{
buff[index++] = ch;
ch = fgetc(fpntr);
}
buff[index] = '\0';
char* tmp;
/*I am not freeing this tmp, will that be a problem if I call this function iteratively*/
tmp = (char*)malloc((int)(index)*sizeof(char));
strcpy(tmp, buff);
return tmp;
}
And in main, I will be calling the grep_stream()
function with valid parameters.
Update: The file that I am trying to add is this: http://textuploader.com/5ntjm