写在前面
-
C++中对文件操作需要包含头文件
<fstream>
-
文件类型分为两种
文本文件:文件以文本对ASCII码形式存储在计算机中
二进制文件:文件以文本的二进制形式存储在计算机中 -
操作文件的三大操作
ofstream:写操作
ifstream:读操作
fstream:读写操作
文本文件的读写操作流程
一、写文件
(1) 流程
- 包含头文件:
<fstream>
- 创建输出流对象:
ofstream ofs;
- 输出流对象调用open方法打开文件:
ofs.open("文件路径", 打开方式)
- 输出数据:
ofs << 数据;
- 关闭流:
ofs.close();
(2) 测试
#include<iostream>
#include<string>
#include <fstream>
using namespace std;
void outputToFile(string file, string content, int mode) {
ofstream ofs;
ofs.open(file, mode);
ofs << content << endl;
ofs.close();
}
int main() {
outputToFile("hello","momo\nmomo\nmo",ios::out);
}
二、读文件
(1) 流程
- 包含头文件:
<fstream>
- 创建输入流对象:
ifstream ifs;
- 输入流对象调用open方法打开文件:
ifs.open("文件路径", 打开方式)
- 四种读取数据的方式 (详见测试代码)
- 关闭流:
ifs.close();
(2) 测试
#include <fstream>
#include<iostream>
#include<string>
using namespace std;
string readFile(string file, int mode) {
ifstream ifs;
ifs.open(file, mode);
string s;
if (!ifs.is_open()) {
cout << "文件打开失败" << endl;
return nullptr;
}
// 第一种方法
// char buf[1024] = {0};
// while (ifs >> buf) {
// s.append(buf);
// }
// 第二种方法:每次读取一行数据到buf中
// char buf[1024] = {0};
// while (ifs.getline(buf,sizeof(buf))) {
// s.append(buf);
// s.append("\n");
// }
// 第三种方法:每次读取一行数据到buf中
// string buf;
// while (getline(ifs,buf)) {
// s.append(buf + "\n");
// }
// 第四种方法:每次读取一个字符到c中
// char c;
// EOF end of file
// while ((c = ifs.get()) != EOF) {
// s.push_back(c);
// }
ifs.close();
return s;
}
int main() {
cout << readFile("hello",ios::in) << endl;
}
三、关于文件的打开方式
打开方式 | 说明 |
---|---|
ios::in | 为读文件而打开文件 |
ios::out | 为写文件而打开文件 |
ios::ate | 写入的初始位置为文件尾 |
ios::app | 以追加方式写入文件 |
ios::trunc | 如果文件存在则删除后重新创建 |
ios::binary | 二进制方式 |
注意:文件打开方式可以配合使用,利用|
操作符,如:ios::out | ios app
二进制文件的读写操作
流程基本和上面一样,下面只展示测试代码
一、写文件
#include<iostream>
#include<string>
#include <fstream>
using namespace std;
class Person {
public:
int age;
char* name;
Person(int age, char* name){
this->age = age;
this->name = name;
}
};
int main() {
ofstream ofs("Person.txt",ios::out | ios::binary);
Person p (11,"张三");
ofs.write((const char*) &p, sizeof(Person));
ofs.close();
}
二、读文件
#include<iostream>
#include<string>
#include <fstream>
using namespace std;
class Person {
public:
int age;
char *name;
Person(int age, char *name) {
this->age = age;
this->name = name;
}
Person() {}
};
int main() {
ifstream ifs;
ifs.open("Person.txt", ios::in | ios::binary);
if (!ifs.is_open()) {
cout << "文件打开失败" << endl;
return 0;
}
Person p;
ifs.read((char*) &p, sizeof(Person));
cout << "姓名:" << p.name << "\n" << "年龄:" << p.age << endl;
ifs.close();
}