二进制文件简单操作(C++书上模板)

#include"pch.h"
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
//二进制数据文件的基本操作
int main() {
	int i, j;
	fstream  f;
	//建立文件,用写方式打开文件
	f.open("C:\\Users\\Lenovo\\Desktop\\Data.dat", ios::out | ios::binary);
	for ( i = 1; i <= 10; i++) {//写入i的只
		f.write((char*)&i, sizeof(int));
	}
	f.close();
	//修改文件
	f.open("C:\\Users\\Lenovo\\Desktop\\Data.dat", ios::in|ios::out | ios::binary);
	for (i = 0; i < 10; i++) {
		f.seekg(long(sizeof(int) *i));//移动流指针
		f.read((char*)&j, sizeof(int));//读出指针所指数据,写入j
		if (j % 2) {
			j += 10;
			f.seekp(-long(sizeof(int)), ios::cur);
			f.write((char*)&j, sizeof(int));//写入修改后的数据
		}
	}
	f.seekg(long( sizeof(int) * 10   ) );//移动到10个数据后f.seekg(n)==f.seekg(n,ios::beg)
	for (i = 91; i <= 95; i++) {
		f.write((char*)&i, sizeof(int));
	}
	//输出
	f.seekg(0, ios::beg);
	for ( i = 0; i < 15; i++) {
		f.read((char*)&j,sizeof(int));
		cout << j << " " ;
	}
	cout << endl;
	cout << "结尾地址" << endl;
	f.seekg(0, ios::end);
	long pos = f.tellg();
	cout << pos << endl;
	f.close();
}

在这里插入图片描述
txt->自定义->txt

#include"pch.h"
#include<iostream>
#include<fstream>
using namespace std;
//txt->自定义的二进制数据文件
void save() {
	char s;
	ifstream instuf("C:\\Users\\Lenovo\\Desktop\\data.txt",ios::in);
	ofstream outf("C:\\Users\\Lenovo\\Desktop\\data.wubindong", ios::out | ios::binary);
	//写数据到二进制数据文件里
	if (!instuf | !outf) {
		cerr << "File couldn't be open" << endl;
		abort();
	}
	//从文本获得数据
	while (instuf.get(s)) {
		outf.put(s);
	}
	instuf.close();
	outf.close();
}
void read() {
	ifstream infile("C:\\Users\\Lenovo\\Desktop\\data.gzhu",ios::in|ios::binary);
	ofstream outfile("C:\\Users\\Lenovo\\Desktop\\data1.txt", ios::out);
	char ch;
	if (!infile) {
		cerr << "File couldn't be open" << endl; abort();
	}
	if (!outfile) {
		cerr << "File couldn't be open" << endl; abort();
	}
	//操作
	while (infile && infile .get(ch)) {
		cout << ch;
		outfile.put(ch);
	}
	infile.close();
	outfile.close();
}
int main() {
	save();
	read();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

广大菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值