C++流类 笔记2
一、对二进制文件流读写
思考:
文本文件和二进制文件的区别?
文本文件: 写数字1, 实际写入的是 ‘1’
二进制文件:写数字1, 实际写入的是 整数1(4个字节,最低字节是1, 高3个字节都是0)
写字符‘R’实际输入的还是‘R’
二、写二进制文件
使用文件流对象的write方法写入二进制数据.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int age;
ofstream outfile;
outfile.open("user.dat", ios::out | ios::trunc | ios::binary);
while (1) {
cout << "请输入姓名: [ctrl+z退出] ";
cin >> name;
if (cin.eof()) { //判断文件是否结束
break;
}
outfile << name << "\t";
cout << "请输入年龄: ";
cin >> age;
//outfile << age << endl; //会自动转成文本方式写入
outfile.write((char*)&age, sizeof(age));
}
// 关闭打开的文件
outfile.close();
system("pause");
return 0;
}
三、读二进制文件
使用文件流对象的read方法.
#include <fstream>
#include <iostream>
#include <string>
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;
}

浙公网安备 33010602011771号