how to write binary file without deleting its previous contents

I am writing a binary file like this:

1
2
3
4
5
6
7
8
9
const int sized = 300000000ULL;
int ad[sized];
...
ad[i] = some value;
...
            FILE* pFile;
            pFile = fopen("obj_pattern.bin", "wb");
            fwrite(ad, 1, sized*sizeof(int), pFile);
            fclose(pFile);


Now how can i again write given binary file obj_pattern.bin with some new values of ad[i] in another program. For example in first program i put ad[] values in the file as 1,2 now how can i again write that same file without deleting the previous saved values 1 and 2?
Last edited on
If you only need to add the data at the end of the file;
You have the append option http://stackoverflow.com/questions/19429138/append-to-the-end-of-a-file-in-c or in c++ you can use fstream's open-mode-append (which can be set when creating the object) http://www.cplusplus.com/reference/ios/ios_base/openmode/
http://www.cplusplus.com/reference/fstream/ofstream/


If you need the data to fit in a certain spot that's not the end;
Supposedly you can do this with an mmap file (memory mapped), but I haven't looked into that enough. Read the first answer here for clues: http://stackoverflow.com/questions/9076049/adding-data-at-beginning-of-file

Otherwise you're stuck with reading the data up to the insertion-point into a buffer, add the new data at the buffer, then continue reading from the original file to the end of that same buffer. When it's all stored in said buffer, output it back to the original file. (Large files can be handled with skillful use of buffers, append, and seekg/tellg).
--- To be safe you should actually write the buffer to a new file, then rename it as the original file just in case the program crashes half way through writing.
Last edited on
Open for append. Also, with something that large, you may want to consider using a sparse file.
Topic archived. No new replies allowed.