m0_60717721 2024-01-20 11:09 采纳率: 33.3%
浏览 5

c++二进制文件读入读出int碰到的问题

我想以二进制的形式写入文件一个整型数字,并能够获取,但是我下面这个代码为什么不能实现这种效果(初学c++,希望指点一下)

int main() {
    fstream fs;
    fs.open("static.txt",ios::in|ios::out | ios::binary);
    int* a = new int[3];
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    fs.write((const char*)a, sizeof(int)*3);
    fs.read((char*)a, sizeof(int)*3);
    fs.close();
    cout << a[0] << endl;
    cout << a[1] << endl;
    cout << a[2] << endl;
}

输出的错误结果:

img

  • 写回答

2条回答 默认 最新

  • micthis 2024-01-20 11:24
    关注

    输入后要将文件输入流设置到开始处再读:

    #include<iostream>
    #include<fstream>
    using namespace std;
    int main() {
        fstream fs;
        fs.open("static.txt",ios::in|ios::out|ios::binary|ios::trunc);
        int* a = new int[3];
        int* b = new int[3];
        a[0] = 1;
        a[1] = 2;
        a[2] = 3;
        fs.write((const char*)a, sizeof(int)*3);
        fs.seekg(0);
        fs.read((char*)b, sizeof(int)*3);
        fs.close();
        cout << b[0] << endl;
        cout << b[1] << endl;
        cout << b[2] << endl;
        delete[] a;
        delete[] b;
        return 0;
    }
    
    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 1月20日

悬赏问题

  • ¥15 office打开卡退(新电脑重装office系统后)
  • ¥300 FLUENT 火箭发动机燃烧EDC仿真
  • ¥15 【Hadoop 问题】Hadoop编译所遇问题hadoop-common: make failed with error code 2
  • ¥15 vb6.0+webbrowser无法加载某个网页求解
  • ¥15 RPA财务机器人采购付款流程
  • ¥15 计算机图形多边形及三次样条曲线绘制
  • ¥15 根据protues画的图用keil写程序
  • ¥200 如何使用postGis实现最短领规划?
  • ¥15 pyinstaller打包错误
  • ¥20 cesm的气溶胶排放文件