A brief analysis of the usage of fstream ifstream and ofstream in C++

  • 2020-04-02 02:35:58
  • OfStack

There is a class in c++ called fstream that allows you to open a file as a stream. Create an object, and then call the open function of the object, which mainly has two parameters, the first parameter is a string, which represents the address of the file, the second parameter is the substitution, such as:


fstream fin("a.txt",ios::in);
if(fin)
{
    cout<<"opened"<<endl;
    fin.close();
}
else
{
    cout<<"not exists"<<endl;
}

Note: If the file does not exist, it fails to open. If this opens in ios::out, then if the file does not exist, it will be created .

There are two subclasses of fstream: ifstream and ofstream. Ifstream opens the file as input by default and fails to open the file if it does not exist. Ofstream opens a file as output by default. If the file doesn't exist, a file is created.

Interested readers can debug the example shown in this article to gain a better understanding of the way fstream manipulates files in C++.


Related articles: