The input and output of C++ uses the iostream header file. The name of this header file means io stream. So today we learn to read and write files. In fact, they are also streams, called file streams , so their header files need to include fstream , which defines three classes. , responsible for file reading, writing, reading and writing operations, as follows:
If we want to read the contents of a file, we can use the ifstream or fstream type. The code is as follows:
#include<fstream>#include<iostream>usingnamespacestd;intmain(){chardata[100];//Open the file in write mode ifstreamfile;file.open(d:\dotcpp.dat);file>>data;cout< <data;//Close the open file file.close();return0;}
Assume that there is already a file dotcpp.dat file under the D drive, and its content is a line of string www.dotcpp.com, then the output result is:
Everyone can experiment on the computer.
It should be noted that for C/C++, the files it can open, read and write are not only txt files. For example, the sample code is a dat file. In fact, any suffix file can be opened, read, written, and closed.