fstream myFile("test.txt", ios::in | ios::out | ios::trunc);
How is this line interpreted by the compiler in C++ file handling?
fstream myFile("test.txt", ios::in | ios::out | ios::trunc);
How is this line interpreted by the compiler in C++ file handling?
ios::out
means that you intend to write to the file in contrast to reading ios::in
. In your case the stream can be used for both reading and writing.
ios::trunc
means that the current file content will be discarded. Compare this to ios::app
where you will append to a file if it exists. ios::trunc
is implied if not ios::in
is specified for example. "When used for an ofstream without ios::app, ios::ate or ios::in, ios::trunc is implied."
Bonus:
iso::binary
means that what you will write will be put verbatim into the file (otherwise for windows \n
could be replaced with \n\r
for example)
fstream : This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.
Also it using multiple flags as per below:
ios::app : Append mode. All output to that file to be appended to the end.
ios::ate : Open a file for output and move the read/write control to the end of the file.
ios::in : Open a file for reading.
ios::out : Open a file for writing.
ios::trunc : If the file already exists, its contents will be truncated before opening the file.
in your case text.txt file will open for reading, writing and if exists then content will truncated.