This is a C ++ class to brush up on the ninth chapter study notes, and other articles with topics can venue: https://www.jianshu.com/nb/39156122
Input and output document is also based on the flow (stream) of, and cout
, cin
similar operations.
Write to the file
Basic conditions
- It must include the header file
fstream
- Header file
fstream
defines processing for outputting theofstream
class - Need to declare one or more
ofstream
variables (objects), and named - You must specify the namespace
std
- We need to
ofstream
associate objects with the file up. One way is to use theopen()
method - After finished with the file, the method should be used
close()
to turn it off - It may be used in conjunction with
ofstream
objects and operators<<
outputs various types of data
Examples of a written document
#include<fstream>
using namespace std;
int main()
{
string myString = "hello world!";
ofstream ourFile;
outFile.open("myFile.txt");
outFile << myString;
outFile.close();
return 0;
}
Read the file
Basic conditions
- It must include the header file
fstream
- Header file
fstream
defines processing for the inputifstream
class - Need to declare one or more
ifstream
variables (objects), and named - We need to
ifstream
associate objects with the file up. One way is to use theopen()
method - After reading the file, the method should be used
close()
to turn it off - It may be used in conjunction with
ifstream
objects and operators>>
to read various types of data - You can use
ifstream
the object andget()
to read a character method,ifstream
the object andgetline()
to read a line of characters - Can be used in combination
ifstream
andcof()
,fai()
like the success of the method to determine whether the input ifstream
When the object itself is used as the test condition, if the last read operation is successful, it will be converted to a Boolean valuetrue
, or is converted tofalse
Examples of a file read
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
string fileName = "myFile.txt";
ifstream inFile;
inFile.open(fileName);
if (!inFile.is_open())
cout << "Can't open the file: " << fileName;
string readText;
inFile >> readText;
if (inFile.eof())
cout << "End of file reached.\n";
else if (inFile.fail())
cout << "Input terminated by data mismatch.\n";
else
cout << "Input terminated for other reasons.\n";
inFile.close();
return 0;
}
Please indicate the source, permanently updated links in this article: https://blogs.littlegenius.xin/2019/08/28/【C- refresher nine] input and output file /