Can fseek() be used to insert data into the middle of a file? - C

John Vulconshinz picture John Vulconshinz · Nov 18, 2012 · Viewed 9k times · Source

I know that the function fseek() can be used to output data to a specific location in a file. But I was wondering if I use fseek() to move to the middle of the file and then output data. Would the new data overwrite the old data? For example if I had a file containing 123456789 and I used fseek() to output newdata after the 5 would the file contain 12345newdata6789 or would it contain 12345newdata.

Answer

Sidharth Mudgal picture Sidharth Mudgal · Nov 18, 2012

Writing data in the "middle" of a file will overwrite existing data. So you would have '12345newdata'.


EDIT: As mentioned in the comments below, it should be noted that this overwrites data without truncating the rest of the file. As an extended version of your example, if you wrote newdata after the 5 in a file containing 1234567890ABCDEFG, you would then have 12345newdataCDEFG, not 12345newdata.