This is what I tried to do with ftell and fseek but I got some really distorted output on the text file when I tried to write to it:
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *fp;
char hw[] = "Homework #2";
char line[512];
char *test;
long i;
fp = fopen("test.txt", "r");
if (fp == NULL)
{
printf("Bad file\n");
return 0;
}
// read in the file
do {
test = fgets(line, sizeof(line), fp);
line[strlen(line)-1] = '\0';
if (strcmp(line, "<!--Comment1-->"))
{
continue;
}
else if (!strcmp(line, "<!--Comment1-->"))
{
i = ftell(fp);
break;
}
} while (test != NULL);
fclose(fp);
fp = fopen("test.txt", "w");
fseek(fp, i, SEEK_SET);
fputs(hw, fp);
return 0;
}
What I was trying to do here was read in until I found the string "<!--Comment1-->" (BTW I'm searching and editing a .html file -- I just put up a text file to test it with -- that is why I'm opening "test.txt" instead of an HTML file) and then store the value of the file pointer in 'i'. Then, I would close the file and open it for writing and goto the spot in the file where 'i' is stored as. This, apparently, didn't work. Any reason why?
Should I just read the file into a char array buffer and go through that and edit? And then I could write the buffer back to the file. Suggestions? Thanks...