【问题标题】:Missing data when reading/writing to stream读取/写入流时缺少数据
【发布时间】:2013-06-21 18:46:20
【问题描述】:

这是一个完整的例子 - 编译并运行,将 map 的内容写入文件并在之后读取它:

#include <map>
#include <fstream>
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
    std::string fname("test.bin");

    std::map<unsigned,unsigned> testMap;
    testMap[0]=103;
    testMap[1]=2;
    testMap[5]=26;
    testMap[22]=4;

    std::ofstream output(fname.c_str(),std::ios_base::binary|std::ios_base::trunc);
    for(std::map<unsigned,unsigned>::iterator iter = testMap.begin();iter != testMap.end();++iter)
    {
        unsigned temp = iter->first;
        output.write((const char*)&temp,sizeof(temp));
        unsigned temp1 = iter->second;
        output.write((const char*)&temp1,sizeof(temp1));
        std::cerr << temp <<" "<<temp1<<" "<<std::endl;
    }
    std::cerr << "wrote bytes.........."<<output.tellp()<<", map size "<<testMap.size()<<std::endl;
    output.flush();
    output.close();

    std::ifstream input(fname.c_str());
    // retrieve length of file:
    input.seekg (0, input.end);
    unsigned streamSize = input.tellg();
    input.seekg (0, input.beg);

    char* buff = new char[streamSize];
    input.read(buff,streamSize);
    cerr << "sizeof of input......"<<streamSize << endl;
    cerr << "read bytes..........."<<input.gcount() << endl;
    ::getchar();
    return 0;
}

它给出以下输出:

0 103 
1 2 
5 26 
22 4 
wrote bytes..........32, map size 4
sizeof of input......32
read bytes...........20

问题是为什么读取的字节与写入的字节不匹配,以及如何读取/写入整个地图。

附:在线编译器给了我 32 个读取字节的预期输出,我在使用 Visual Studio 2010 proffesional 编译时得到了错误的输出。

【问题讨论】:

    标签: c++ stl ifstream ofstream


    【解决方案1】:

    确保您将文件作为二进制文件打开。

    【讨论】:

      猜你喜欢
      • 2011-12-25
      • 2016-02-21
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-03
      • 2013-02-21
      相关资源
      最近更新 更多