记录C++操作文件步骤, 方便以后直接复用
一 文件操作三个类
1 ofstream: 写操作
2 ifstream: 读操作
3 fstream: 读写操作
fstream同时具有上两个类的功能,若对文件安全性无特殊需求,可以全都使用fstream操作,省心。
文件操作分两类:文件文件和二进制文件
写文件流程
① 包含头文件 #include <fstream>
② 创建流对象
写文件流对象 ofstream ofs;
读文件流对象 ifstream ifs;
③ 打开文件 ofs.open(文件路径,打开方式);
④ 写数据 ofs << “data”;
⑤ 关闭文件 ofs.close();
文件打开方式:
使用二进制写文件方式:ios::out | ios::binary,其他二进制打开方式类似。
二 代码实现
txt文件读写:
#include <iostream>
// 1 包含头文件
#include <fstream>
#include <string>
using namespace std;
int main() {
//写文件操作 =============================================
//2 创建流对象
ofstream ofs;
//3 打开文件,会在当前目录自动生成文件test_write_file.txt
ofs.open("test_file.txt", ios::out);
//4 写数据
ofs << "data" << endl;
ofs << "this is a test code" << endl;
//5 关闭文件
ofs.close();
//读文件操作 =============================================
ifstream ifs;
//打开文件,并判断是否打开成功
ifs.open("test_file.txt", ios::in);
if (!ifs.is_open()) {
cout << "file open fail" << endl;
return -1;
}
//读取文件数据4种方式
//读取方式1
// char buf1[1024] = {0};
// while (ifs >> buf1) {
// cout << buf1 << endl;
// }
//读取方式2
// char buf2[1024] = {0};
// while (ifs.getline(buf2, sizeof(buf2))) {
// cout << buf2 << endl;
// }
//读取方式3
string buf3;
while (getline(ifs, buf3)) {
cout << buf3 << endl;
}
//读取方式4
// char c;
// while ((c = ifs.get()) != EOF) { //end of file, 文件结尾标志
// cout << c;
// }
//不要忘记关闭文件
ifs.close();
return 0;
}
以上,关于读文件,我更喜欢方式3,看个人喜好可以在方式1,2,3中选一个,不推荐方式4,效率太低。
二进制文件读写:
#include <iostream>
// 1 包含头文件
#include <fstream>
#include <string>
using namespace std;
class Teacher {
public:
char name[64];
int age;
};
int main() {
//二进制写文件 =============================================
ofstream ofs;
Teacher t1 = {"li ming", 33};
ofs.open("teacher.txt", ios::out | ios::binary);
// &t1类型是Teacher,write方法需求char*类型,需要强制转换
// 函数原型:ostream& write(char *buffer, int len)
ofs.write((const char *) &t1, sizeof(Teacher));
ofs.close();
//二进制读文件 =============================================
ifstream ifs;
ifs.open("teacher.txt", ios::in | ios::binary);
if (!ifs.is_open()) {
cout << "file open fail" << endl;
return -1;
}
// 存储的是Teacher对象,最后也应由Teacher对象接收
Teacher t2;
ifs.read((char *) &t2, sizeof(Teacher));
cout << "name = " << t2.name << endl;
cout << "age = " << t2.age << endl;
ifs.close();
}