-
seekp and binary files
I am writing a programme which creates a binary file, but because the programme is generating bits of information which need to go in different sections of the file I am trying to use seekp to jump around in the output file to the correct location.
This is producing very unpredictable results and I wonder if it is because the length of the file has not been defined, and you can't use seekp to jump ahead of where the last byte was written.
If this is so, is there a way of specifying the length of the file when you create it, so that you can use seekp to move around in it?
Grateful for any advice.
-
Well, if you are creating a new file and want it to be a certain size, I would fill it with a value (such as 0) up to the size you want. You can use the fill_n function in the <algorithm> header to do that:
Code:
#include <fstream>
#include <algorithm>
#include <iterator>
int main()
{
std::ofstream output("output.txt",std::ios::binary|std::ios::out);
// Create a 500 byte file stuffed with 0's
std::fill_n(std::ostream_iterator<char>(output),500,0);
}