Jump to content

Using fseek then fwrite overwrites data...how to avoid this?


blurredvision

Recommended Posts

I have a script that creates a text file in 'a' mode, writes to it, then closes it.  Then it checks to see if a variable has been set, and if so, it will reopen the same file in 'r+' mode, use fseek to go to a particular spot that is specified, write the new data, then closes the file.

 

All of this works fine except that when the file is opened a second time and data is written at the new spot specified by fseek, it writes over the data that is already there instead of just inserting it inbetween characters.  It's sort of like when typing in a word processer, and you press the insert key on the keyboard, it will replace a character with the character you just typed, instead of just pushing everything to the right and inserting the new character like normal.  I want it to push everything to the right and insert, not overwright.

 

How can I fix this, or can I?

The code is doing what the functions were designed to do.

 

To "insert" information into the middle of the file, you need to actually write the whole output the way you want.

 

The easiest way would be to create a new temporary file (in case any errors occur you will still have your original file.) Read the existing file up to the point where you want to insert the new information, write the first part of the file to the temporary file, write the new information to the temporary file, read the remainder of the old file, write that to the temporary file, close the files, check for any errors, and if no errors delete the original file and rename the temporary file to the original file name.

The code is doing what the functions were designed to do.

 

To "insert" information into the middle of the file, you need to actually write the whole output the way you want.

 

The easiest way would be to create a new temporary file (in case any errors occur you will still have your original file.) Read the existing file up to the point where you want to insert the new information, write the first part of the file to the temporary file, write the new information to the temporary file, read the remainder of the old file, write that to the temporary file, close the files, check for any errors, and if no errors delete the original file and rename the temporary file to the original file name.

 

I understand.  It sucks because I'll have to modify my script now, but I understand.  ;)  Thanks a lot. :D

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.