how to insert and delete characters in the middle of file

I have a problem that I want to insert and delete some chars in the middle of a file. fopen() and fdopen() just allow to append at the end.

Is there any simple method or existing library that allow these actions? Thanks in advance.:confused:

Isn't there any other clever and efficient way to do that?

Driver gave you the clever efficient way. :smiley:

anyway, thanks veru much :wink:

If you have the memory, you might want to read the whole file into memory, manipulate it there and then dump the results back to disk.

That could be faster depending on a number of factors e.g number of search operations, insert/delete operations, disk performance or size of file.

But this method of loading all the data and dumping the useful data back to the file works like putting the data to a newly created file. My question is whether there exist a more efficient library for me to insert/delete characters in any position of a file. Anyway, thanks for your response.

Yes, I agree, which is why I say "could". A lot depends on machine specs and the problem itself. The problem described is quite simple, but a mail merge application, indexing or sorting application will require due consideration to performance.

My point to the OP was quite simple and old fashioned: memory is faster than disk!

( I hope that is still true these days :smiley: )

Peace :slight_smile:

FILE *fp = 0;

const char *path = "/the/path";

fp = fopen(path, "r+");

if (fp)
{
/* move to the appropriate location using fseek() /
/
perforn necessary updates */
fclose(fp);
}
else fprintf(stderr, "Cannot open file %s\n", path);

if u specify the "r+" option the file is opened for update (both reading and writing). u can navigate within the file using the fseek() lib function. this technique allows u to overwrite existing characters located anywhere within a file. i 've used it and it works.