I've been trying to write a C program that will get the string from between two substrings for weeks now. I cant get it to work.
I made some progress, but my program has a bug I cant find, it
works on some strings some times but not others.
I've tried, but I new to C and need help.
The data is inside a large (40 meg) text file I read in , here are examples...
[CODE]
Pesudo code example...
char string[80] = "This is a test string, it has som err < ors insi[} de of it."
char d1 = ", it";
char d2 = "} d";
printf ("extracted substring= %s", getsub(string,d1,d2));
printf output= has som err < ors insi[}
Here's my DEFECTIVE C Coding attempt...
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <assert.h>
#include <limits.h>
int main(void)
{
FILE *fp;
char s[80];
char fname[] = "tst-file";
const char *PATTERN1 = "<h . som >errw";
const char *PATTERN2 = "</h gg-txtw>";
if ((fp= fopen(fname, "r")) == NULL) {
printf("cannot open file");
exit(1);
}
while(!feof(fp)) {
fgets(s,80,fp);
char *target = NULL;
char *start, *end;
if ( start = strstr( s, PATTERN1 ) )
{
start += strlen( PATTERN1 );
if ( end = strstr( start, PATTERN2 ) )
{
target = ( char * )malloc( end - start + 1 );
memcpy( target, start, end - start );
target[end - start] = '\0';
}
}
if ( target ) printf( "%s\n", target );
free( target );
}
fclose(fp);
return 0;
}