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