C++文件操作完全指南:从文本读写到二进制文件处理

文本文件

1.文本文件 ASCII码

2,二进制文件 二进制存

操作文件三大类

1.ofstream写操作

2.ifstream读文件

3.fstream 读写文件

写文件

1.#include <fstream

2.创建流对象

ofstream ofs;

3.打开文件

ofs.open("文件路径",打开方式);

4.写数据

ofs<<"写入的数据";

5.关闭文件

ofs.close();

文件打开方式

ios::in 以只读方式打开文件(只能读,不能写)

ios::out 以只写方式打开文件→ 会清空原有内容

ios::app 以追加方式写文件→ 不会清空,写在文件末尾

ios::ate 打开文件后,定位到文件末尾(但可以修改前面内容)

ios::trunc 打开时清空文件内容(默认和 out 一起生效)

ios::binary 以二进制模式打开(不做文本转换)

javascript 复制代码
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
using namespace std;
void test01(){
	//1.包含头文件
	//2.创建流对象
	ofstream ofs;
	//3.指定打开方式
	ofs.open("test.txt", ios::out);
	//4.写内容
	ofs << "姓名:张三" << endl;
	ofs << "年龄:18" << endl;
	ofs << "性别:男" << endl;
	//5.关闭
	ofs.close();
}
int main() {
	test01();
}

读文件

1.包含头文件

#include<fstream

2.创建流对象

ifstream ifs;

3.打开文件并判断文件是否打开成功

ifs.open("文件路径",打开方式);

4.读数据

四种方式读取

5.关闭文件

ifs.close()

javascript 复制代码
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void test01(){
	//1.包含头文件
	//2.创建流对象
	ifstream ifs;
	//3.打开文件 并且判断是否打开成功
	ifs.open("test.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)) {
		cout << buf << endl;
		//getline结束会返回false或者EOF
	}
	//第四种
	char c;
	while ((c = ifs.get()) != EOF) {
		cout << c;
	}

	//5.关闭文件
	ifs.close();
}
int main() {
	test01();
}

用二进制写文件

javascript 复制代码
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class person {
public:
	char m_name[100];
	int m_age;
};
void test01(){
	ofstream ofs;
	ofs.open("text.txt", ios::out | ios::binary);
	person p = { "张三",18 };
	ofs.write((const char*)&p, sizeof(p));
	ofs.close();

}
int main() {
	test01();
}

用二进制读文件

javascript 复制代码
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class person {
public:
	char m_name[100];
	int m_age;
};
void test01(){
	ifstream ifs;
	ifs.open("test.txt", ios::in | ios::binary);
	if (!ifs.is_open()) {
		cout << "文件打开失败" << endl;
		return;
	}
	person p;
	ifs.read((char*)&p, sizeof(person));
	cout << "姓名" << p.m_name << endl;
	cout << "年龄" << p.m_age << endl;
	ifs.close();
}
int main() {
	test01();
}
相关推荐
程与留3 小时前
15_国际化和本地化:tr()、ts 文件、QM 文件、多语言切换
c++·qt
程与留5 小时前
14_Qt 样式表(QSS)入门(语法、选择器、美化实战)
c++·qt
欧特克_Glodon14 小时前
OpenCV计算机视觉开发入门与实践<二十七>:图像分割概述
c++·人工智能·opencv·计算机视觉
蒸蒸yyyyzwd14 小时前
cpp 选手秋招学习笔记 day21
c++·面试·八股
Interview Aid11214 小时前
TikTok OA 四题分享|半小时内 AC,题目基本都是实现题
java·开发语言·算法·面试·职场和发展
CoderIsArt21 小时前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
AI情绪识别开源1 天前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
「QT(C++)开发工程师」1 天前
C++ auto 用法详解
开发语言·c++
OPEN-F1 天前
C++STL教程:容器适配器与实用工具
开发语言·c++