1.文本文件
C++文件包含头文件<fstream>
文件类型两种:
a.文本文件:文件以文本的ASCII码形式存储
b.二进制文件:文件以文本的二进制形式存储
操作文件三个类:
ofstream:写文件
ifstream:读文件
fstream:读写文件
写文件:
包含头文件
#include<fstream>
创建流对象
ofstream ofs;
打开文件
ofs.open("文件路径",打开方式);
写数据
ofs<<"写入的数据";
关闭文件
ofs.close();
打开方式:
ios::in | 为读文件而打开文件 |
ios::out | 为写文件而打开文件 |
ios::ate | 初始位置:文件尾(直接在文件尾开始写) |
ios::app | 追加方式接文件 |
ios::trunc | 如果文件存在,先删除再创建 |
ios::binary | 二进制方式 |
注意:文件打开方式可以配合使用,利用|操作符
ios::binary|ios::out
写文件
#include<iostream>
using namespace std;
#include<fstream>
void test01() {
ofstream ofs;
ofs.open("test.txt", ios::out);
ofs << "姓名:张三" << endl;
ofs.close();
}
int main() {
test01();
return 0;
}
读文件
包含头文件
创建流对象
ifstream ifs;
打开文件并判断是否文件打开成功
ifs.open("文件路径",打开方式);
读数据四种方法
关闭文件
ifs.close();
读文件
#include<iostream>
using namespace std;
#include<fstream>
#include<string>
void test01() {
ifstream ifs;
ifs.open("test.txt", ios::in);
//ifs.is_open()返回值是一个bool数据类型,0/1,打开失败返回0
if (!ifs.is_open()) {
cout << "文件打开失败" << endl;
return;
}
//读文件
//第一种
/*char buf[1024] = {0};
while (ifs >> buf) {
cout << buf <<"00" << endl;
}*/
//第二种
//char buf1[1024] = { 0 };
//while (ifs.getline(buf1, sizeof(buf1))) {
// cout << buf1<<"0000" << endl;
//}
//第三种
string buf;
while(getline(ifs,buf)) {
cout << buf << endl;
}
//关闭文件
ifs.close();
}
int main() {
test01();
return 0;
}
2.二进制文件
打开方式ios::binary
写二进制文件
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class person {
public:
char m_name[64];
int m_age;
};
void test01() {
ofstream ofs;
ofs.open("person.txt", ios::out | ios::binary);
person p = { "张三",18 };
//数据类型要转换
ofs.write((const char*)&p, sizeof(person));
ofs.close();
}
int main() {
test01();
return 0;
}
读二进制文件
二进制读文件
void test02() {
ifstream ifs;
ifs.open("person.txt", ios::in | ios::binary);
if (!ifs.is_open()) {
cout << "文件打开失败" << endl;
return;
}
person p1;
ifs.read((char*)&p1, sizeof(person));
cout << p1.m_age << p1.m_name << endl;
}