I am writing a binary file in C++, where I traverse to a particular location and need to over-write the contents with the new one. I know the contents of the integer size, so I keep track of the location and over write it. Seems like, ofstream write function inserts or appends the variable. Is there a way, where I can over write, instead of appending or inserting in a file
long word = sizeof(int) + sizeof(long) + sizeof(long);
std::ofstream file_write(filename, std::ios::out|std::ios::binary);
file_write.seekp(word);
long pos = file_write.tellp();
file_write.write((char *)&some_integer,sizeof(int));
file_write.close()
//some other location
file_write.seekp(pos);
file_write.write((char *)&some_other_integer,sizeof(int));
//Here some_integer should be over written by some_other_integer. Is there a way to do it?
That will be like
value1,value2,value3
I might be able to replace value 2 with value 5.
then it should look like
value1,value5,value3
You need to add
std::ios::truncto your open parameters, as in:That will truncate the file, discarding any existing content.