So I have the following piece of code however when I try to run the function more than once, it does not work.
Any help would be great. I have tried to free the memory allocated to target but this function only works on the first call.
Edit: Have moved fopen to function and have included fclose. Also changed fopen error to perror().
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
FILE *fo;
int main (int argc, char *argv[]) {
readFile("<Text1>","</Text1>");
readFile("<Text2>","</Text2>");
return (0);
}
int readFile(char *start_tg, char *end_tg) {
char line[100];
char *start;
char *end;
char *target = NULL;
char pattern1[30];
char pattern2[30];
fo = fopen("doc.lst","r");
if(fo == NULL){
perror("doc.lst");
exit(1);
}
strcpy(pattern1,start_tg);
strcpy(pattern2,end_tg);
while(fgets(line, sizeof(line), fo)) {
if((start = strstr(line,pattern1)) != null) {
start += strlen(pattern1);
if ((end = strstr(start,pattern2)) != null) {
target = malloc( strstr(start,pattern2) - strstr(line,pattern1) + 1);
if(target) {
fprintf(stdout,"\n String %s\n",target);
free(target);
}
memcpy( target, start, end - start);
target[end - start] = '\0';
}
}
}
fclose(fo);
return (0);
}