无法从文件中读取简单的二进制整数? (C ++) [英] Cannot read simple binary integers from file? (C++)

查看:115
本文介绍了无法从文件中读取简单的二进制整数? (C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的code是简单地为这样的:

My code is simply as this:

更新时间:

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char **argv)
{
  ifstream r("foo.bin", ios::binary);
  ofstream w("foo.bin", ios::binary);
  int i;

  int ints[10] = {0,1,2,3,4,5,6,8,9};
  w.write((char*)&ints, sizeof(ints));

  int in_ints[10];
  r.read((char*)&in_ints, sizeof(in_ints));

  for(i = 0;i < 10;i++) {
    cout << in_ints[i] << " ";
  }
  cout << endl;

  return 0;
}

现在,写部分似乎是成功的,例如运行od命令与32位多头(我的系统是32位),将显示正确的序列,其中包括一个十六进制转储。

Now, the write portion appears to be successful, for example running the od command with 32 bit longs (my system is 32 bit) will display the correct sequence, including a hex dump.

阅读不过,我得到的随机序列,而负整数不应该发生的(这是分手了,而且大多零作为我的整数是小,符号位不应该上。)

Reading however, I get random sequences such and negative integers that should not happen (it is split up, and mostly zeros as my integers are small, the sign bits should not be on.)

你看为什么我的读法未能奏效,当它真的是我写的方法相反?

Do you see why my read method has failed to work, when it is really an opposite of my write method?

推荐答案

尝试 w.flush() w.close() r.read 。问题是,当你写它通常bufferes文本,不会保存在文件中。所以没有什么真的在文件 r.read

try w.flush() or w.close() before r.read. the problem is when you write it usually bufferes text and doesn't save it in file. so there is nothing realy in file for r.read.

这篇关于无法从文件中读取简单的二进制整数? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆