Before a small project need to write some configuration files, but actually need to configure the content is very little, so directly with TXT storage, and now a little collation of the next TXT read and write operation and code, written two functions convenient after the call, conveniently shared here slightly ~
Create or open txt and write txt code:
void Write txt (string name, string content, bool overwrite) {
ofstream write (name, overwrite? ios::trunc:ios::app);
if (write. Is_open ()) {//If successful
write << content << Endl;
Write. Close ();
}
}
Read txt content and cout code
Void reads txt and displays (string name) {
fstream read file; read the file. Imbue (Std::locale ("CHS"));
Read the file. Open (first name);
while (! Read file. EOF ()) {
The thing read by string;
Read the document >> read something;
cout << read something << Endl;
}
Read the file. Close ();//closing is a good habit
}
The overall code to run is as follows:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void writes TXT (string name, string content, bool overwrite);
If you do not create
void read txt and display (string name);
int main () {
//Create and write txt
write txt ("rigid. txt", "Gou Li Country Life and death, its due to misfortune to avoid the trend.") ", false);
True to overwrite, false to write
/read txt and display
read txt and display ("rigid. txt");
System ("pause");
}
void Write txt (string name, string content, bool overwrite) {
ofstream write (name, overwrite? ios::trunc:ios::app);
if (write. Is_open ()) {//If successful
write << content << Endl;
Write. Close ();
}
}
Void reads txt and displays (string name) {
fstream read file; read the file. Imbue (Std::locale ("CHS"));
Read the file. Open (first name);
while (! Read file. EOF ()) {
The thing read by string;
Read the document >> read something;
cout << read something << Endl;
}
Read the file. Close ();//closing is a good habit
}
The results are as follows:
Run one time:
Run two times:
Have a good study!