C++ - 文件读写(fstream)
因为平时写算法很少用到文件读取,写的十分基础,带将来有了进一步认识再来补充。
参考:
《Essential C++》
文章目录
- 一、 文件读写操作头文件:
- 二、输入方法
- 2.1 定义ofstream对象(以输出模式开启test_data.txt):
- 2.2 追加模式(append mode):
- 2.3 完整示例
- 三、读取方法
- 3.1 定义ifstream对象(以输入模式开启test_data.txt):
- 3.2 完整示例
- 四、IO方法
一、 文件读写操作头文件:
#include <fstream>
二、输入方法
2.1 定义ofstream对象(以输出模式开启test_data.txt):
- 如果文件名不存在,则会在当前文件目录下创建一个新文件。
- 文件中原有数据会被清空。
ofstream outfile("test_data.txt");
“outfile”返回值为布尔值,代表文件是否打开成功
2.2 追加模式(append mode):
不丢弃原文件中数据,在原文件中数据末尾开始写入。
ios_base::app
使用案例:
ofstream outfile("test_data.txt", ios_base::app);
2.3 完整示例
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile("test_data.txt", ios_base::app);
if (!outfile)
{
cerr << "Oops! Unable to save session data!\n";
}
else {
outfile << "Write something..." << endl;
}
return 0;
}
三、读取方法
3.1 定义ifstream对象(以输入模式开启test_data.txt):
若文件打开成功,则文件的写入位置设定在文件的起始位置处。
ifstream infile("test_data.txt");
3.2 完整示例
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile("test_data.txt");
if (!infile)
{
cerr << "Oops! File opening failed!\n";
}
else {
string name;
while(infile >> name) {
cout << "Find Name: " << name << endl;
}
}
return 0;
}
四、IO方法
若希望同时读写同一个文件,则需要以追加模式打开。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream iofile("test_data.txt", ios_base::in|ios_base::app);
if (!iofile)
{
cerr << "Oops!\n";
}
else {
// 开始读取前,将文件重新定位至起始处
iofile.seekg(0);
}
return 0;
}