问题
Possible Duplicate:
C++ Filehandling: Difference between ios:app and ios:ate?
What is the difference between these two file opening modes ?
ios:ate sets the get/put pointer position to the end of the file => reading/writing will begin from end, but how is it different from ios::app, which again opens a file in append mode...but when I have created a ofstream and opened it in ios:app mode, the put stream pointer still points to the beginning, how does the appending work then ?
Also I understand that ifstream, ofstream and fstream are high level classes to manage the underlying stream buffer. So does it mean that even in ios:app mode i can read data from a file ?
回答1:
app
comes from 'append' - all output will be added (appended) to the end of the file. In other words you cannot write anywhere else in the file but at the end.
ate
comes from 'at end' - it sets the stream position at the end of the file when you open it, but you are free to move it around (seek) and write wherever it pleases you.
回答2:
ate
simply positions you at the end of file after opening, and nothing else. It's not much use on an ofstream
, at least without other flags, since the file will have been truncated anyway, so the beginning is the end. (To avoid truncation, and still be able to write anywhere in the file, you need to or in ios::in
as well, even if you're not going to read.)
app
prevents the truncation of an existing file, and causes every write to go to the end of the file. Atomically, if possible; if other processes are writing to the same file, your write should still go to the end. Note however that this refers to the actual system level write. If, however, you are writing lines which are less than the buffer size, and you terminate each line with std::endl
, you can count on each line being appended atomically, regardless of what other processes might be doing with the file. To be effective, you'll probably want to use pubsetbuf
on the filebuf
as well, to ensure a minimum buffer size.
In practice, I don't think I've ever used either of them, or found them of any use. The buffering issues with app
, in particular, have generally led me to write my own streambuf
, with conceptually unlimited buffering (an std::vector<char>
as buffer), which opens the underlying system file with the equivalent of app
, but guarantees only writing to it when explicitly flushed (as with `std::endl).
回答3:
If you look at e.g. this reference, you will see:
app seek to the end of stream before each write
and
ate seek to the end of stream immediately after open
This means that ios::app
only writes at the end, but that ios::ate
reads and writes at the end by default. However, with ios::ate
you can seek freely in the file, but with ios::app
you will always write at the end, no matter what position you set for the writing pointer.
来源:https://stackoverflow.com/questions/12929378/difference-between-iosapp-and-iosate