0

How to make fseek not overwrite what was at the given position when used with fwrite?

I am opening a file with

file = fopen(filename, "r+");

and then use

fseek (file, pos, SEEK_SET);

to go to the position I need, using

fwrite(text, 1, text_size, file);

to write the data.

example:

Say, I want to add '7' at position 3:

abcdef

I want this to be

abc7def
SkyRipper
  • 155
  • 5
  • 15

2 Answers2

1

You can't insert into a file. The only way to accomplish that would be saving the rest of the file somewhere, write your new stuff, then append the rest of the file from where you've saved it. But you have to re-write the whole part of your file after what you want to insert.

Guntram Blohm
  • 9,667
  • 2
  • 24
  • 31
  • Do all the text editors the mankind made work by copying the file when i make a single character change? – SkyRipper Dec 14 '13 at 10:01
  • No, they load the file into memory, handle your edits in memory, then write (the whole file!) back when you choose to save. – Guntram Blohm Dec 14 '13 at 10:02
  • is there any way, in any language, even assembly? My file will be hundreds megabytes... – SkyRipper Dec 14 '13 at 10:04
  • @SkyRipper: What did you think would happen? Somehow, more room has to be made to accommodate the new character. Where is that space going to come from if you want your entire text stream to remain contiguous? – dreamlax Dec 14 '13 at 10:04
  • @SkyRipper: The limitation is not a programming language limitation. The operating system and the file system do not offer an API that inserts bytes in the middle of a file. Some programs, like MS Word some years ago, worked around this by making custom database-like file formats that strung hunks of text together non-linearly; but, then, you could only read the file in MS Word. Text editors do their editing out-of-line (either in memory, or with a combination of memory and temp files), and then replace the original file on saving. – Joe Z Dec 14 '13 at 10:06
  • Do all operating systems and filesystems do this, or are there exceptions? – SkyRipper Dec 14 '13 at 10:11
0

Fseek won't overwrite anything. You can overwrite what's at the position you seek to if you use fwrite, fputs, fputc or a similar function after the fseek.

Guntram Blohm
  • 9,667
  • 2
  • 24
  • 31
  • very correct, how to avoid this? – SkyRipper Dec 14 '13 at 09:52
  • What do you want to avoid? Overwriting after fseek? Then don't use a function that writes to the file. If your question is: How can i make any of the writing functions write to the end of the file instead of the position where you've fseek()ed to - use fseek(fp, 0, SEEK_END). – Guntram Blohm Dec 14 '13 at 09:54
  • please see the example above – SkyRipper Dec 14 '13 at 09:57