【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();
}

读取没问题

相关推荐
小年糕是糕手3 分钟前
【数据结构】常见的排序算法 -- 选择排序
linux·数据结构·c++·算法·leetcode·蓝桥杯·排序算法
huangyuchi.8 分钟前
【Linux网络】Socket编程实战,基于UDP协议的Dict Server
linux·网络·c++·udp·c·socket
青衫码上行1 小时前
【Java Web学习 | 第七篇】JavaScript(1) 基础知识1
java·开发语言·前端·javascript·学习
星释1 小时前
Rust 练习册 10:多线程基础与并发安全
开发语言·后端·rust
yunhuibin2 小时前
无锁化编程——c++内存序使用
c++
披着羊皮不是狼2 小时前
多用户博客系统搭建(1):表设计+登录注册接口
java·开发语言·springboot
zzzyyy5384 小时前
C++之vector容器
开发语言·c++
uotqwkn89469s6 小时前
如果Visual Studio不支持C++14,应该如何解决?
c++·ide·visual studio
xunyan62346 小时前
面向对象(上)-封装性的引入
java·开发语言
Maple_land7 小时前
Linux复习:冯·诺依曼体系下的计算机本质:存储分级与IO效率的底层逻辑
linux·运维·服务器·c++·centos