How to edit a random position of a file with fstream apis?

J

James Fang

Hi all,

I need to edit a random position of a file, for e.g, the 500th
byte.
To keep portability, I would like to use standard C++ instead of
os apis.
Could you help on this?
Thanks
 
V

Victor Bazarov

James said:
I need to edit a random position of a file, for e.g, the 500th
byte.
To keep portability, I would like to use standard C++ instead of
os apis.
Could you help on this?

What exactly do you need help with? Open the file for read+write.
Position the stream at 500. Write the new byte. Close the stream.

V
 
J

James Kanze

What exactly do you need help with? Open the file for read+write.
Position the stream at 500. Write the new byte. Close the stream.

Maybe he tried that and it didn't work.

There are several issues you have to pay attention to, at least
if you want to be portable:

-- First and foremost, the stream must be opened in binary
mode, and you must imbue the stream (or at least the
filebuf) with locale "C". Otherwise, a statement such as
"500th byte" doesn't really have any meaning.

-- The second thing is that if you really want to be strictly
portable, you have to use the two argument forms of seek,
e.g.: "myFile.seekp( 500, std::ios::beg )". In most
implementations, the one argument form will also work, but
according to the standard, there is in fact no guarantee
that an integral value will convert implicitly to a
streampos, and no guarantee that if it converts, the results
have any real relationship to the physical position in the
file.

And finally, as you say, you must open the file in read+write
mode (ios::in | ios::eek:ut), even if you're just writing; opening
in write only mode always truncates (unless you specify the
ios::app flag, but in that case, all writes are always to the
end of file, regardless of where you might be positionned
beforehand).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,184
Messages
2,570,978
Members
47,561
Latest member
gjsign

Latest Threads

Top