Inserting text into file
-
I am trying to write data to the middle of file. I use fseek to navigate to the correct position and then use fprintf() to write my buffer to the file. But I find that fprintf() overwrites any data that may be after the current position of the file pointer i.e. I have a text file with the following text: oranges_oranges_oranges_oranges I use this C code to manipulate the file FILE *pFile = fopen("mytext.txt", "r+"); fseek(pFile, 10, SEEK_SET); fprintf("_apples_"); fclose(pFile); The results: oranges_or_apples_anges_oranges My old data was overwritten! Does anyone have a usable method
-
I am trying to write data to the middle of file. I use fseek to navigate to the correct position and then use fprintf() to write my buffer to the file. But I find that fprintf() overwrites any data that may be after the current position of the file pointer i.e. I have a text file with the following text: oranges_oranges_oranges_oranges I use this C code to manipulate the file FILE *pFile = fopen("mytext.txt", "r+"); fseek(pFile, 10, SEEK_SET); fprintf("_apples_"); fclose(pFile); The results: oranges_or_apples_anges_oranges My old data was overwritten! Does anyone have a usable method
-
I am trying to write data to the middle of file. I use fseek to navigate to the correct position and then use fprintf() to write my buffer to the file. But I find that fprintf() overwrites any data that may be after the current position of the file pointer i.e. I have a text file with the following text: oranges_oranges_oranges_oranges I use this C code to manipulate the file FILE *pFile = fopen("mytext.txt", "r+"); fseek(pFile, 10, SEEK_SET); fprintf("_apples_"); fclose(pFile); The results: oranges_or_apples_anges_oranges My old data was overwritten! Does anyone have a usable method
First I would say that you should understand that the access mode "r+" means read with update... where update means "change". Even though it is, in theory, possible to add data to the middle of a file, I don't know of any way to do it using a language like C. You could possition the file pointer to the insertion point, copy the remainder to a temp holding space such as memory, or a scratch disk file, reposition the file pointer to the insertion offset and overwrite the file with the insert data, then append the data from the temp holding space.