RaKo
RaKo

Reputation: 77

What happens when ios::in mode is specified with an output file stream?

What is the purpose of ios::in and ios::out modes while creating file streams in c++? I have created an output file stream as ofstream myout("file.txt",ios::in); This is an output file stream but ios::in mode is specified. What is the effect of ios::in mode in output stream and similarly ios::out mode in input file stream?

I have looked here, but couldn't understand.

Upvotes: 0

Views: 411

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596116

Per std::basic_filebuf<CharT,Traits>::open(), which better explains what the various flag combinations actually do:

The file is opened as if by calling std::fopen with the second argument (mode) determined as follows:

mode openmode & ~ate Action if file already exists Action if file does not exist
"r" in Read from start Failure to open
"w" out, out|trunc Destroy contents Create new
"a" app, out|app Append to file Create new
"r+" out|in Read from start Error
"w+" out|in|trunc Destroy contents Create new
"a+" out|in|app, in|app Write to end Create new
"rb" binary|in Read from start Failure to open
"wb" binary|out, binary|out|trunc Destroy contents Create new
"ab" binary|app, binary|out|app Write to end Create new
"r+b" binary|out|in Read from start Error
"w+b" binary|out|in|trunc Destroy contents Create new
"a+b" binary|out|in|app, binary|in|app Write to end Create new

If openmode is not one of the modes listed, the open() fails.

If the open operation succeeds and openmode & std::ios_base::ate != 0 (the ate bit is set), repositions the file position to the end of file, as if by calling std::fseek(file, 0, SEEK_END), where file is the pointer returned by calling fopen. If the repositioning fails, calls close() and returns a null pointer to indicate failure.

If the associated file was already open, returns a null pointer right away.

Upvotes: 3

Related Questions