前言
C++文件操作学习笔记
引入头文件
文件操作的基本步骤
- 创建流对象
- 打开文件
- 读写数据
- 关闭文件
文本文件的读写
写文件
<src>
:文件路径
文件的打开方式
ios::in
:读文件
ios::out
:写文件
ios::ate
:初始位置文件尾部
ios::app
:追加方式写文件
ios::trunc
:覆盖方式写文件
ios::binary
:二进制方式操作文件
<data>
:需要写入的数据
1 2 3 4 5 6 7 8
| ofstream ofs;
ofs.open("<src>", ios::out);
ofs << <data>
ofs.close();
|
创建流对象时直接传递参数
1 2 3 4 5 6
| ofstream ofs("<src>", ios::out);
ofs << <data>
ofs.close();
|
读文件
1 2 3 4 5 6 7 8
| ifstream ifs;
ifs.open("<src>", ios::in);
...
ofs.close();
|
创建流对象时直接传递参数
1 2 3 4 5 6
| ifstream ifs("<src>", ios::in);
...
ofs.close();
|
读文件时读数据的方式
得到字符数组
1 2 3 4 5
| char buf[1024] = { 0 } while (ifs >> buf) { cout << buf << endl; }
|
得到字符数组
1 2 3 4 5
| char buf[1024] = { 0 } while (ifs.getline(buf, sizeof(buf))) { cout << buf << endl; }
|
得到字符串
1 2 3 4 5
| string buf; while (getline(ifs, buf)) { cout << buf << endl; }
|
得到字符
- 一个字符一个字符的读取,遇到文件结尾标识符时停止,每次得到的是字符
1 2 3 4 5
| char c; while ((c = ifs.get()) != EOF) { cout << buf << endl; }
|
二进制文件的读写
写文件
<date>
:需要写入的数据,不仅仅是字符串,也可以是对象
1 2 3 4 5 6 7 8
| ofstream ofs;
ofs.open("<src>", ios::out | ios::binary);
ofs.write(<data>, sizeof(<date>));
ofs.close();
|
创建流对象时直接传递参数
1 2 3 4 5 6
| ofstream ofs("<src>", ios::out | ios::binary);
ofs.write(<data>, sizeof(<date>));
ofs.close();
|
读文件
(char *)&p
:如果写入的数据是对象,那么读取的时候也可以读取到对象
1 2 3 4 5 6 7 8 9
| ifstream ifs;
ifs.open("<src>", ios::in | ios::binary);
Persion p; ifs.write((char *)&p , sizeof(Persion));
ifs.close();
|
创建流对象时直接传递参数
1 2 3 4 5 6 7
| ifstream ifs("<src>", ios::in | ios::binary);
Persion p; ifs.write((char *)&p , sizeof(Persion));
ifs.close();
|
判断文件是否存在
1 2 3 4 5 6 7 8
| ifstream ifs; ifs.open("<src>", ios::in);
if (!ifs.is_open()) { ... }
|
判断文件是否为空
1 2 3 4 5 6 7 8 9 10
| ifstream ifs; ifs.open("<src>", ios::in);
char ch; ifs >> ch;
if (ifs.eof()) { ... }
|
清空文件内容
1 2
| ofstream ofs; ofs.open("<src>", trunc::in);
|
完成
参考文献
哔哩哔哩——黑马程序员