【C++】文件操作

文件操作

程序运行时产生的数据都属于临时数据,程序一旦运行结束都会被释放,通过文件可以将数据持久化,C++中对文件操作需要包含文件 <fstream>
操作文件三大类:
1、ofstream:写操作
2、ifstream:读操作
3、fstream:读写操作

一、文本文件

文件以文本的ASCII码形式存储在计算机中

(一)写文件

步骤:

1、包含头文件cpp#include <fstream>

2、创建流对象ofstream ofs;

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

4、写数据ofs<<"写入的数据";

5、关闭文件ofs.close();

打开方式 解释
ios::in 为读文件而打开文件
ios::out 为写文件而打开文件
ios::ate 初始位置:文件尾
ios::app 追加方式写文件
ios::trunc 如果文件存在先删除,再创建
ios::binary 二进制方式

文件打开方式可以配合使用,利用|操作符

例如用二进制写文件:ios::binary|ios::out

cpp 复制代码
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void test() {
	ofstream ofs;
	ofs.open("test.txt", ios::out);
	ofs << "姓名:张三" << endl;
	ofs << "年龄:18" << endl;
	ofs << "性别:女" << endl;
	ofs.close();
}

读文件

步骤:

1、包含头文件cpp#include <fstream>

2、创建流对象ifstream ifs;

3、打开文件,判断是否打开成功ifs.open("文件路径",打开方式);

4、写数据:四种方式读取

5、关闭文件ifs.close();

cpp 复制代码
void test1() {
	ifstream ifs;
	ifs.open("test.txt", ios::in);
	if (!ifs.is_open()) {
		cout << "文件打开失败" << endl;
		return;
	}
	//读数据1
	/*char buf[1024] = { 0 };
	while (ifs >> buf) {
		cout << buf << endl;
	}*/

	//读数据2
	/*char buf[1024] = { 0 };
	while (ifs.getline(buf,sizeof(buf))) {
		cout << buf << endl;
	}*/

	//读数据3
	/*string buf;
	while (getline(ifs, buf)) {
		cout << buf << endl;
	}*/

	//读数据4,EOF表示文件尾,不推荐
	char c;
	while ((c = ifs.get()) != EOF) {
		cout << c;
	}
	ifs.close();
}

二、二进制文件

文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂他们。

打开方式指定为ios::binary

(一)写文件

主要利用流对象调用成员函数write

函数原型:ostream& write(const char* buffer,int len);

参数解释:字符指针buffer 指向内存中一段空间,len是读写的字节数。

cpp 复制代码
#include <iostream>
#include <string>
//包含头文件
#include <fstream>
using namespace std;
class S {
public:
	char name[64];
	int age;
};
void test2() {
	//创建流对象
	ofstream ofs("s.txt", ios::out | ios::binary);
	//打开文件
	//ofs.open("s.txt", ios::out | ios::binary);
	//写数据
	S s1 = { "李四",20 };
	ofs.write((const char*)&s1, sizeof(S));
	//关闭
	ofs.close();
}

会有乱码,但不影响读数据就行

(二)读文件

二进制方式读文件主要利用流对象调用成员函数read

函数原型:istream& read(char *buffer,int len);

参数解释:字符指针buffer 指向内存中一段存储空间,len是读写的字节数。

cpp 复制代码
void test() {
	ifstream ifs;
	ifs.open("s.txt", ios::in | ios::binary);
	if (!ifs.is_open()) {
		cout << "读取失败" << endl;
		return;
	}
	S s1;
	ifs.read((char*)&s1, sizeof(S));
	cout << "姓名:" << s1.name <<"\t年龄:" << s1.age << endl;
	ifs.close();
}

读取没问题

相关推荐
YaoYuan93232 小时前
C++ 类型推导(第一部分)
c++
HAH-HAH2 小时前
【Python 入门】(2)Python 语言基础(变量)
开发语言·python·学习·青少年编程·个人开发·变量·python 语法
递归不收敛2 小时前
一、Java 基础入门:从 0 到 1 认识 Java(详细笔记)
java·开发语言·笔记
夜猫逐梦3 小时前
【VC】 error MSB8041: 此项目需要 MFC 库
c++·mfc
zhangfeng11333 小时前
win7 R 4.4.0和RStudio1.25的版本兼容性以及系统区域设置有关 导致Plots绘图面板被禁用,但是单独页面显示
开发语言·人工智能·r语言·生物信息
姓刘的哦4 小时前
Qt中的QWebEngineView
数据库·c++·qt
C_player_0014 小时前
——贪心算法——
c++·算法·贪心算法
SundayBear4 小时前
QT零基础入门教程
c++·qt
子午5 小时前
Python的uv包管理工具使用
开发语言·python·uv
kyle~5 小时前
排序---插入排序(Insertion Sort)
c语言·数据结构·c++·算法·排序算法