Use of ios__in, ios__out, ios__trunc in C++

Catalog

One, ios::in

II, ios::out

Three, ios::trunc

Four, combined

In C++, ios::in and ios::out are flags defined in the iostream library that control the behavior of file flow objects such as fstream, ifstream, and ofstream.

One, ios::in

The ios::in: flag is used to open the file in input mode, that is, to read data from the file. If you use ifstream to open a file, this flag is applied by default. For example:

std::ifstream ifs("example.txt", ios::in); 

This opens a file named “example.txt” in read-only mode.

II, ios::out

The ios::out: flag is used to open the file in output mode, that is, to write data to the file. If you use ofstream to open a file, this flag is used by default. For example:

std::ofstream ofs("example.txt", ios::out); 

This opens or creates a file named “example.txt” in write-only mode for writing data.

Three, ios::trunc

ios::trunc Use this flag when you want to open a file and delete its contents. If the file already exists, its contents are emptied when you open the file. Typically used with the ios::out flag to ensure that a file is written starting with an empty file. For example:

std::ofstream ofs("example.txt", ios::out | ios::trunc); 

This will open the file named “example.txt,” if it already exists, its contents will be emptied and you can start writing new data to it.

Four, combined

These flags can be used in combination to meet different file operational requirements. For example, if you want to open a file and read data from it and create it if it doesn’t exist, you can do this:

std::fstream fs("example.txt", ios::in | ios::out | ios::trunc); 

This combination opens the file in read-write mode and its contents are emptied if the file already exists. If the file does not exist, a new file is created.

This document is transferred from https://blog.csdn.net/Mm66f/article/details/135424819,If there is any infringement,Please contact to delete。