读/写流时丢失数据

3

这里是一个完整的例子 - 编译和运行,将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专业版编译时,我得到了错误的输出。
1个回答

2

请确保您以二进制文件的形式打开文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接