c/c++读取二进制文件

#include <string>
#include <fstream>
#include <iostream>
using  namespace  std;
  
typedef  struct
{
    int  x;
    int  y;
}point_t;
  
int  main(int  argc, char* argv[])
{
    /* 二进制文件的写入 */
    ofstream ofs("test.dat", ios::binary);
    /* 写入字符串 */
    string a = "You are welcome!"
    int  n = a.size();
    ofs.write((char*)&n, sizeof(int));
    ofs.write(a.c_str(), sizeof(char) * n);
    /* 写入结构体 */
    point_t b = {80, 51};
    ofs.write((char*)&b, sizeof(point_t));
    ofs.close();    
  
    /* 二进制文件读取 */
    ifstream ifs("test.dat", std::ios::binary);
    /* 读取字符串 */
    int  m;
    ifs.read((char*)&m, sizeof(int));
    char* c = new  char[m + 1];
    ifs.read(c, sizeof(char) * m);
    c[m] = '\0';
    /* 读取结构体 */
    point_t d;
    ifs.read((char*)&d, sizeof(point_t));
    ifs.close();
  
    /* 显示读取数据 */
    cout << c << endl;
    cout << '('  << d.x << ','  << d.y << ')'  << endl;
  
    return  0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值