【C++】C++文件操作-文本文件/二进制文件
0.前言
一、文本文件
1.写文件
代码
#include <iostream>
using namespace std;
#include <fstream> //头文件包含//**************************************
//文本文件 写文件
void test01() {//1.包含文件 fstream//2.创建流对象ofstream ofs;//3.指导打开方式ofs.open("text.txt", ios::out);//4.写内容ofs << "姓名:王哈哈" << endl;ofs << "年龄:19" << endl;//5.关闭文件ofs.close();
}//*************************************
int main() {test01();//**************************************system("pause");return 0;
}
结果
2.读文件
#include <iostream>
using namespace std;
#include <fstream> //头文件包含
#include <string>//**************************************
//文本文件 写文件
void test01() {//1.包含文件 fstream//2.创建流对象ifstream ifs; //fstream fs;也是可以的//3.指导打开方式ifs.open("text.txt", ios::in);if (!ifs.is_open()) {cout << "文件打开失败" << endl;return;}//4.读内容//第一种方式//char buf[1024] = { 0 };//while (ifs >> buf) {// cout << buf << endl;//}第二种方式//char buf[1024] = { 0 };//while (ifs.getline(buf, sizeof(buf))) {// cout << buf << endl;//}//第三种方式(学这个)string buf;while (getline(ifs, buf)) { //得加上string头文件cout << buf << endl;}第四种方式,不推荐,因为是一个一个字符读,太慢了//char c;//while ((c = ifs.get()) != EOF) { //EOF end of file// cout << c;//}//5.关闭文件ifs.close();
}//*************************************
int main() {test01();//**************************************system("pause");return 0;
}
二、二进制文件
1.写文件
#include <iostream>
using namespace std;
#include <fstream> //头文件包含
#include <string>class Person {
public:char m_Name[64];int m_Age;
};
//**************************************
//二进制文件 写文件
void test01() {//1.包含头文件 fstream//2.创建输出流对象ofstream ofs("person.txt", ios::binary | ios::out);//3.打开文件/*ofs.open("text.txt", ios::out | ios::binary);*/Person p = { "张三",19 };//4.写内容ofs.write((const char*)&p, sizeof(p));//5.关闭文件ofs.close();
}//*************************************
int main() {test01();//**************************************system("pause");return 0;
}
2.读文件
#include <iostream>
using namespace std;
#include <fstream> //头文件包含
#include <string>class Person {
public:char m_Name[64];int m_Age;
};
//**************************************
//二进制文件 读文件
void test01() {//1.包含头文件 fstream//2.创建输出流对象ifstream ifs("person.txt", ios::binary | ios::in);//3.打开文件/*ofs.open("text.txt", ios::out | ios::binary);*/if (!ifs.is_open()) { //判断文件是否打开cout << "文件打开失败" << endl;}//4.写内容Person p;ifs.read((char*)&p, sizeof(p));cout << "姓名:" << p.m_Name << " 年龄:" << p.m_Age << endl;//5.关闭文件ifs.close();
}//*************************************
int main() {test01();//**************************************system("pause");return 0;
}