二进制文件输入输出与文本文件想类似
下列是输入:
#include<Windows.h>
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ofstream outfile;
string name;
int age;
outfile.open("小猪.bat", ios::out | ios::trunc | ios::binary);
while (1) {
cout << "请输入姓名[输入ctrl+z结束]:";
cin >> name;
if (cin.eof()) {
break;
}
cout << "请输入年龄:";
cin >> age;
outfile.write((char*)&age, sizeof(age));
}
outfile.close();
system("pause");
return 0;
}
下列是输出:
using namespace std;
int main(){
string name;
int age;
ifstream infile;
infile.open("user.dat", ios::in | ios::binary);
while (1) {
infile >> name;
if (infile.eof()) { //判断文件是否结束
break;
}
cout << name << "\t";
// 跳过中间的制表符
char tmp;
infile.read(&tmp, sizeof(tmp));
//infile >> age; //从文本文件中读取整数, 使用这个方式
infile.read((char*)&age, sizeof(age));
cout << age << endl; //文本文件写入
}
infile.close();
system("pause");
return 0;
}