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?
As others have already told you, you have to do it manually, and use fseek in order to get to the place in which you have to insert or add characters. You can easily add new characters in the middle by doing the following:
If you want to delete characters in the middle, then this is more tricky. Actually you cannot make a file shorter. You have two possibilities: in the first one, you just
In the second possibility, you:
Point four is "tricky", because there is no standard (portable) way to do this. One possiblity is to use the operating system system calls in order to truncate the file. Another, simpler possibility is to just fwrite EOF in point 4. The file will be probably larger than it should be, but it will do the trick.
Use fseek function to move the file pointer to the appropriate location of the file and then you can perform a write there. But, for this you should know how many bytes from the end or begining of the file your preferred area for write is.
There is no simple method. You have do it manually. For example:
Taking into account what Baltasarq posted, I wrote the following lines. You need to know the position where you want to insert the chars
long Fin;
long lSize;
fseek(fd, 0L, SEEK_END);
Fin = ftell(fd);//get the old file size
fseek(fd, position, SEEK_SET);//"position" must be declared and initialized
char * buffer;
lSize = Fin - position;//length from where you want to insert the chars to the eof
buffer = (char*) malloc(sizeof(char) * lSize);
size_t result = fread(buffer, 1, lSize, fd);//fread (Fin - position) into buffer
fseek(fd, position, SEEK_SET);//fseek to position
fputs(word, fd);//word is a char pointer that contains the text to be inserted
fputs(buffer, fd);//fwrite the buffer
I actually used this code (after some modifications) to triplicate the words that contain every vowel, in a given file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With