3

I'm writing a method to replace a specified string from a binary file and it writes NULLs before 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);
2
  • What exactly is your question? Commented Apr 1, 2011 at 10:39
  • This piece of code destroys the data from the binary file. I only wants to replace some bytes. What have I done wrongly? Commented Apr 1, 2011 at 10:53

1 Answer 1

4

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.