0

I have a binary file already open in memory,

FILE* fptr = fopen(filename, "wb");

I already wrote some data to this file:

fwrite(fptr, ...);

After writing all my data, how do I prepend data at the beginning of this file?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
manatttta
  • 3,054
  • 4
  • 34
  • 72
  • 9
    To my knowledge, no function for prepending data exists, nor do I know of many file systems that support it. You can simulate a prepend by writing a new file with the data you wish to add to the front then copying the original contents after it. This is essentially what the filesystem would need to do in order to prepend data itself. – Mr. Llama Jul 05 '16 at 16:45
  • @Mr.Llama: well, it's not true that the file system would necessarily have to be so stupid - it *could* be optimized for such a usage pattern. Adding a "partial" cluster at the beginning of the cluster chain would be way cheaper than shifting all the existing data through the allocated clusters. Think `std::deque` vs `std::vector` (with the bonus that in most file systems data is already stored in fixed size pages). – Matteo Italia Jul 05 '16 at 17:33
  • 1
    Do you mean "prepend" rather than "append"? (The word "append" means adding at the end.) Specifically, are you trying to insert data at the beginning of the file, so that the data currently at offset 0 will be at offset N (where N is the number of bytes you insert)? Or do you want to overwrite any existing data at the beginning of the file? – Keith Thompson Jul 05 '16 at 18:21
  • @KeithThompson I meant prepend. After a lot of investigation I found out it probably can't be done.. – manatttta Jul 06 '16 at 08:28

1 Answers1

0

I belive that there is no cross-plattform way of doing so...

My solution would be the following:

  1. Read in all data from the file
  2. Write new data to the file
  3. Append previously (1.) read data at the end

This will lead to the result you wanted. If you need only one writing operation, you should first manage all your data in memory before writing it to a file...

mame98
  • 1,271
  • 12
  • 26