【问题标题】:Vector data written to binary file isn't the same when read back into another vector, why?当读回另一个向量时,写入二进制文件的向量数据不一样,为什么?
【发布时间】:2012-05-05 00:48:19
【问题描述】:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "ReadText.h"
using namespace std;

const string FILE_NAME = "TopicIinBasic.txt";

template<typename T>
char * as_bytes( T &inType );


int main()
{
    vector<int> vec(2, 2);

    vector<int> receive(2);

    fstream write( "myFile.dat", ios::out | ios::binary );

    write.write( as_bytes(vec[0]), sizeof(vec[0] * 2) );

    write.close();

    fstream read( "myFile.dat", ios::in | ios::binary );

    read.read( as_bytes(receive[0]), sizeof(vec[0] * 2) );

    cout << receive[0] << ' ' << receive[1] << endl;    

    return 0;
}

template<typename T>
char * as_bytes( T &inType )
{
    void* addr = &inType;

    return static_cast<char*>(addr);
}

我先将vec的内容写入二进制文件。然后关闭文件。然后以阅读模式再次打开它。然后我尝试将二进制文件的内容放入receive。但是当我显示receive 的内容时,输出是2 0,而不是2 2。为什么会这样?

谢谢。

【问题讨论】:

  • 实际的文件内容是什么(如果你在十六进制编辑器中打开它)?
  • 另外,const string FILE_NAME 有什么用?还有#include "ReadText.h"?

标签: c++ file binary


【解决方案1】:

您正在获取表达式vec[0] * 2 的大小,它与vec[0] 的大小相同。结果,你只写了一个元素!

* 2 移到括号外将修复它。 (为了清楚起见,我还把它移到了前面。)

write.write( as_bytes(vec[0]), 2 * sizeof(vec[0]) );

【讨论】:

  • 请注意,同样的问题也存在于 read 调用中。
  • 对——同样的代码,同样的问题。很明显,修复它们!
  • 只是想指出这一点,因为如果 OP 没有注意到,修复写入仍然会显示问题 ;)
猜你喜欢
  • 1970-01-01
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-05
  • 1970-01-01
  • 2016-02-14
  • 1970-01-01
相关资源
最近更新 更多