读取/写入流时缺少数据
Missing data when reading/writing to stream
以下是完整的示例-编译并运行,将映射的内容写入文件,然后立即读取:
#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专业版编译时得到了错误的输出。
确保将文件作为二进制文件打开。
相关文章:
- C++将文本文件中的数据读取到结构数组中
- 为 Sql 服务器实现 odbc 包装器.将数据库数据读取为字符或要求驱动程序将数据转换为 C 类型
- 如何将来自文本文件的数据读取到结构的int阵列中
- 如何将不同长度的数据读取到 2D 数组中
- 从TXT文件到C 的结构向量中的数据读取
- 将sqlite原始数据读取到qbyTearray
- 如何将来自输入TXT文件的数据读取到2 C 数组中
- 使用MQQueue将数据读取到缓冲区中时麻烦
- 在 VC++ 中将类数据读取和写入二进制文件
- 将数据从数据读取器终端获取到GUI(QtCreator)
- C 将数据读取到一个结构,但它跳过了我的一个获取线,使该元素空白
- C++将二进制数据读取到结构
- c++我需要将文件中的数据读取到多维数组中,然后用一种数据类型对数组进行排序.怎样
- 对齐数据:速度取决于恒定数据读取的相对采样大小和采样频率
- 如何将文件中的数据读取到数组中
- 如何使用Visual C++应用程序的完整应用程序数据读取Minidump的应用程序数据
- 如何将csv文件数据读取到数组中
- 用C++将格式化的数值数据读取到数组中
- 正在从文件中将数据读取到结构数组中
- 将分离的数据读取到数组结构c++中