C++语言基础 例程 二进制文件及其顺序读写

贺老师的教学链接  本课讲解


对比ASCII文件和二进制文件

//将short int x=12345写入文本文件
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main( )
{
    short int x=12345;
    ofstream outfile("binary.dat");

    if(!outfile)
    {
        cerr<<"open error!"<<endl;
        exit(1);//退出程序
    }
    outfile<<x<<endl;
    outfile.close( );
    return 0;
}

//将short int x=12345写入二进制文件
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main( )
{
    short int x=12345;
    ofstream outfile("binary.dat",ios::binary);
    if(!outfile)
    {
        cerr<<"open error!"<<endl;
        exit(1);//退出程序
    }
    outfile.write((char*)&x,2);
    outfile.close( );
    return 0;
}

将数据以二进制形式存放在磁盘文件中
#include<iostream>
#include <fstream>
#include<cstdlib>
using namespace std;
struct student
{
    char name[5];
    int num;
    int age;
    char sex;
};


int main( )
{
    student stud[3]=
    {
        {"Li",25,18,'f'},
        {"Fun",32,19,'m'},
        {"Wang",40,17,'f'}
    };
    ofstream outfile("stud.dat",ios::binary);
    if(!outfile)
    {
        cerr<<"open error!"<<endl;
        exit(1);//退出程序
    }
    for(int i=0; i<3; i++)
        outfile.write((char*)&stud[i],sizeof(stud[i]));
    cout<<"任务完成,请查看文件。"<<endl;
    outfile.close( );
    return 0;
}


将二进制文件中的数据读入内存
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
struct student
{
    char name[5];
    int num;
    int age;
    char sex;
};
int main( )
{
    student stud[3];
    int i;
    ifstream infile("stud.dat",ios::binary);
    if(!infile)
    {
        cerr<<"open error!"<<endl;
        abort( );
    }
    for(i=0; i<3; i++)
        infile.read((char*)&stud[i],sizeof(stud[i]));
    infile.close( );
    for(i=0; i<3; i++)
    {
        cout<<"NO."<<i+1<<endl;
        cout<<"name:"<<stud[i].name<<endl;
        cout<<"num:"<<stud[i].num<<endl;;
        cout<<"age:"<<stud[i].age<<endl;
        cout<<"sex:"<<stud[i].sex<<endl<<endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值