c++ - 读取/写入流时丢失数据

标签 c++ stl ifstream ofstream

这是完整的例子——编译和运行,将映射的内容写入文件并在之后立即读取:

#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++ - 读取/写入流时丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17242292/

相关文章:

c++ - 为什么我会收到此 ifstream 错误?

c++ - 复制构造函数定义和声明区别?

c++ - 双缓冲系统并发处理的设计?

c++ - 找到第n大元素

c++ - 为第二个范围内的重复项设置差异,替代 remove_copy

c++ - 以二进制模式从文件中读取 block 到缓冲区并将该缓冲区写入另一个文件

python - 将 ctypes int** 转换为 numpy 二维数组

c++ - 重载 vector<T> 的输出流运算符

c++ - 为什么使用 std::forward 禁用模板参数推导?

c++ - 从 C++ 文件中读取包含 std::vector 的对象