简体   繁体   English

ofstream <<运算符未将正确大小写入文件

[英]ofstream << operator doesn't write correct size to file

I'm very unsure of file IO when it comes to this, and I'm really confused. 关于此,我非常不确定文件IO,我真的很困惑。 When I use the insertion stream operator to push some short integers into the file the size of the file is not what I expect: 当我使用插入流运算符将一些短整数推入文件时,文件大小不是我所期望的:

std::ofstream outFile("myFile.raw", std::ios::binary | std::ios::out);

std::vector<short> list;
for (int i = 0; i < 100; ++i) list.push_back(1);
for (auto i : list) outFile << i;
outFile.close();

This creates a file that is 100 bytes big. 这将创建一个100字节大的文件。 I'm not understanding, the short is supposed to be two bytes. 我不明白,短消息应该是两个字节。 The documentation shows that the << operator is overloaded for many different types, so I thought that this writes the correct data type. 文档显示<< <<运算符对于许多不同的类型都是重载的,因此我认为这会写入正确的数据类型。 I guess not. 我猜不会。

Thanks. 谢谢。

You are using formatted output . 您正在使用格式化输出

The short int s are written as digits. short int被写为数字。 Each digit is 1 which is a single char of a single byte. 每个数字是1这是一种单一char的单个字节的。

So the total is 100. If you had short int s containing double digit numbers, say 22 , then the size would be 200. 因此总数为100。如果您的short int包含两位数,例如22 ,则大小为200。


As an alternative you could either use unformatted output or you could cast the data to char s, which together with the binary flag you have set will write the data without formatting it. 或者,您可以使用未格式化的输出 ,也可以将数据charchar ,这些char与您设置的binary标志一起将写入数据而无需格式化。 Something to keep in mind when writing raw char s is that you will have to consider how many bytes and how you want to order the bytes in the file. 编写原始char时要记住的一点是,您将必须考虑多少个字节以及如何对文件中的字节进行排序


Formatted output and input could be more convenient in general. 格式化的输出和输入通常可能更方便。 As an alternative to writing the file with raw char s it would be better to look into serialization . 作为用原始char写入文件的替代方法,最好研究序列化

The reason is - as mentioned in the comments an in the previous answer - that operator << is formatted output and writes value 1 as a single digit (which consists of only one character). 原因是-如上一个答案的注释中所述-运算符<<被格式化后输出,并且将值1写为一个数字(仅包含一个字符)。

Just for the sake of showing how a short int could be written as binary, see the following code: 只是为了说明如何将short int编写为二进制,请参见以下代码:

std::ofstream outFile("myFile.raw", std::ios::binary | std::ios::out);

std::vector<short> list;
for (int i = 0; i < 100; ++i) list.push_back(1);
for (auto i : list) outFile.write((const char*)&i, sizeof(i));
outFile.close();

std::ifstream in("myFile.raw", std::ifstream::ate | std::ifstream::binary);
std::cout << "File size: " <<  in.tellg() << std::endl;
// prints out: File size: 200
in.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM