Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use std::fstream to deal with files in C++

Shulou Source: shulou.com Published: 2022-06-02 05:44:54 10月13日 Update

This article will explain in detail how to use std::fstream to deal with files in C++. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

1. Use open () and close () to open and close files

(1) to use the fstream class, you need to use open () to open the file

Fstream myFile; / / instantiate a file object myFile.open ("firstFile.txt", ios_base::in | ios_base::out | ios_base::trunc); / / Open the file firstFile.txt. You can choose three modes: if (mfFile.is_open ()) / / check whether open () is successful {Dosomething (); / / read or write myFile.close () / / Don't forget to close the file stream to save its contents.

Open ("path and name of file name", ios_base::in | ios_base::out | ios_base::trunc)

The first parameter: the path and name of the file to be opened (if no path is provided, the default is the current directory of the application)

The second parameter: is the open mode of the file. Ios_base::in (readable file), ios_base::out (writable file), ios_base::trunc (recreate the specified file even if it exists)

(2) in addition to using open () to open a file, you can also use the constructor of the fstream class to open a file

/ use the constructor to open the file fstream myFile ("firstFile.txt", ios_base::in | ios_base::out | ios_base::trunc); / / if you only want to open the file to write ofstream myFile ("firstFile.txt", ios_base::out); / / if you only want to open the file to read ifstream myFile ("firstFile.txt", ios_base::in)

Note: whether you use the member method open () or the constructor to open a file stream, it is recommended that you use is_open () to check whether the file open operation was successful before using the file stream object.

two。 Create a text file using open () and use the operator

Tags: File content text operator operation success function pattern path caching processing parameter name object article method more directory knowledge program Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Shulou Information Xiaomi OPPO Reno vpn