c++二进制文件的输入输出

二进制文件输入输出与文本文件想类似
下列是输入:

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值