代码实践:
#include <iostream>
using namespace std;
#include <fstream>
#include <string>
int main()
{
//文件写出操作
#if 0
//ofstream OutFile("hmj.txt"); //如果文件之前没有就会创建,有就会覆盖
ofstream OutFile("hmj.txt", ios_base::app); //如果文件之前没有就会创建,有就追加而不覆盖
if (!OutFile)
{
cerr << "打开失败!" << endl;
}
else
{
OutFile << "hehe" << " " << 1 << " " << 2 << endl;
}
#endif
//文件读入操作
#if 0
ifstream InFile("hmj.txt");
if (!InFile)
{
cerr << "此文件不存在" << endl;
}
else
{
string s1;
int a = 0, b = 0;
while (InFile >> s1 >> a >> b)
{
cout << s1 << " " << a << " " << b << endl;
}
}
#endif
//文件读写操作
#if 0
fstream IOFile("hmj.txt", ios_base::app | ios_base::in); //这里少加了ios_base::in会导致后面读操作失败 但是少了ios_base::out写操作没有影响
if (!IOFile)
{
cerr << "打开失败" << endl;
}
else
{
//先写(app方式)
IOFile << "hmj" << " " << 1 << " " << 2 << endl;
//再读
IOFile.seekg(0);
string s;
int b = 0, c = 0;
while (IOFile >> s >> b >> c)
{
cout << s << " " << b << " " << c << endl;
}
}
#endif
system("pause");
return 0;
}
今天是20200227 《数据结构与算法图解》我来啦😍!