Replacing data in binary file with fstream and seekp
I'm writing a method to replace a specified string from a binary file and it writes NULLs bef开发者_运维技巧ore the position I set with seekp, then writes the string and closes the stream. I only want to replace some bytes in the file. Before this piece of code I tried out with ofstream with ios::binary and ios::out flags. What's wrong to destroy all data in the file? Before this piece of code, I open the file with an instance of ifstream to read the same position verifyng the first byte in the string. I only comment this for information.
Thank you all!
The code:
fstream ofs();
ofs.open(nomArchBin,ios::in | ios::out | ios::binary);
if (!ofs.good()) {
cout << "...";
return;
}
ofs.seekp(despEnArchivo,ios::beg);
char* registroChar = registroACadena(reg);
ofs.write(registroChar,cabecera.tamanioReg);
I know this sounds silly, but the only way to open a file for writing
and not to truncate it is to open it for reading as well: if you're
really doing ios::in | ios::out | ios::binary
, it should work. (But
since you obviously reentered the code, and didn't copy/paste it, I'm
not sure if this is really what you did.)
Other points you have to pay attention to when trying to seek:
- The file must be open in binary mode, and imbued with the "C" locale. (IMHO, a file opened in binary mode should ignore the locale, but this isn't what the standard says.)
- Both `seekg` and `seekp` have the same effect; using either changes the position of the other.
- The only function which allows seeking to an arbitrary location is the two argument seek; the one argument form can only be used to seek to a position previously obtained by a tell.
精彩评论