C++笔记--文件操作--IO类--fstream
以前,有一个段子,把大象放入冰箱中需要3步:
第一步,打开冰箱门;
第二步,放入大象;
第三步,关闭冰箱门。
在程序中对给定文件进行文件操作(读取数据与写入数据)也是3步:
第一步:打开文件;
第二步,进行操作;
第三步,关闭文件。
#include <fstream>
using namespace std;
// 221020 一开始,对于写入文档的认识:
int main(){
//1 初始化文件
ofstream outFile;
outFile.open("data_221020.csv", ios::out); // 打开模式可省略
//2 写入文件
outFile << "x" << ',' << "y" << ',' << "z"<< endl; // 末尾endl类似于回车键
outFile << "1" << ',' << "2" << ',' << "3" << endl;
//3 关闭
outFile.close();
}
文件显示:
x,y,z
1,2,3
若没有在第一行输入"endl":
x,y,z1,2,3
out mode 模式打开文件会将上一次的文件覆盖,即丢弃原有数据。
IO对象无拷贝与赋值。
1. fstream 头文件
- ifstream 给定文件读取数据
- ofstream 给定文件写入数据
1.1 模式与描述
- 1 ios::app 追加
- 2 ios::ate 打开文件定位文件的末尾
- 3 ios::in 读取
- 4 ios::out 写入
- 5 ios::trunc 若文件存在, 内容会被截取.
可选择2个或者多个组合使用。
1.2 ofstream
// 打开文件
void open(const char *filename, ios::openmode mode);
// 关闭文件
void close();
// 判断文件打开了吗?
bool is_open();
追加模式
int main(){
//1 初始化文件
ofstream outFile;
outFile.open("data_221020.csv", ios::app); // 打开模式可省略S
//2 写入文件
outFile << "4" << ',' << "5" << ',' << "1" << endl;
//3 关闭
outFile.close();
return 0;
}
文件显示:
x,y,z
1,2,3
4,5,1
1.3 ifstream
将内容逐行写入到一个string的vector中
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int main(){
char data[10];
vector<string> p;
printf("%d\n", p.empty());
//1 初始化文件
ifstream inFile("data_221020.csv");
//2 写入文件
while(! inFile.eof()) //成员函数eof(), 可以判断文件是否读到文件尾, 如果是返回真
{
inFile >> data;
cout << data << endl;
p.push_back(data);
// cout << p.size() << endl;
}
p.pop_back(); // 最后有一行空行,会导致两边读取,故弹出最后一个元素
cout << p.size() << endl;
//3 关闭
inFile.close();
return 0;
}
打印显示:
1
x,y,z
1,2,3
4,5,1
4,5,1
3
IO库属于C++标准库,除了上述出现的fstream
与iostream
头文件,还有sstream
头文件没有涉及,后续补充。