Making changes to an open text file is complicated by the fact that you probably want to work line by line, but file positioning (eg using fseek) works on a character (or more truly, a byte) position. The easiest way to work is probably to read in every line and write it back out again to a temp file (after making any required changes), then swap the files.
But if you don't want to do that, ie, you want to work on the file "in place", here's something to get you started, with some functioning examples of some of the commands involved:
Code:
#include <stdio.h>
#include <string.h>
int main() {
int got, total=0, offset, i, dif;
char *ptr, find[]="change this", replace[]="to that", buffer[64]; /* presume short lines */
FILE *file=fopen("tmp.txt", "r+");
while ((got=fread(buffer,1,64,file))) { /* 64 objects of 1 byte each */
if ((ptr=strstr(buffer,"change this"))) {
offset=ptr-buffer; /* some pointer arithmetic */
fseek(file,total+offset,SEEK_SET);
fwrite(replace,1,strlen(replace),file);
dif=strlen(find)-strlen(replace);
for (i=0;i<dif;i++) fwrite(" ",1,1,file);
fseek(file,total+got,SEEK_SET); /* back to end of line */
}
total+=got;
}
return 0;
}
This does not change the length of the file, it "blanks out" the extra characters, so if the file looked like that:
Code:
blah blah blah
blah change this blah
blah blah
it will now look like this:
Code:
blah blah blah
blah to that blah
blah blah
Which is part of why it's easier to write in and out line by line, or else read the entire file into memory, work on it and write it back out (no need for a temp file).