我正在尝试将各种值导出到一个二进制文件中,比如int和简单的struct。下面是一些代码:
#include <iostream>
#include <fstream>
#include <cstdint>
using namespace std;
template<class T> void writeToStream(ostream& o, T& val)
{
o.write((char*)&val, sizeof(T));
cout << o.tellp() << endl; //always outputs 4
}
struct foo {
uint16_t a, b;
};
int main()
{
foo myFoo = {42, 42};
ofstream test("test.txt", ios::binary);
writeToStream(test, myFoo);
test.close();
}程序应该生成一个4字节长的输出文件。但当我打开它时,它只有2个字节长。如果我将myFoo.a和myFoo.b更改为包含256或更大的值(需要存储超过1个字节),则文件将变为4字节长。我在Win7上使用Visual Studio11开发人员预览版;我还没有检查其他系统或编译器上是否也发生了同样的事情。对于a或b低于256的值,如何使其正确输出?
发布于 2012-04-01 09:11:54
文件只能由理解其存储格式的程序回读。Notepad++无法理解您的文件的存储格式,因此它无法读回文件并正确地呈现它。要么以Notepad++理解的格式写入文件,例如ASCII文本,要么仅使用能够理解您编写的格式的程序读取文件。
发布于 2012-04-01 09:23:37
我清理了你的代码,如下所示。虽然我不知道为什么旧代码输出两个字节,但新代码确实输出了四个字节。
#include <iostream>
#include <fstream>
#include <cstdint>
using std::cout;
using std::endl;
using std::uint16_t;
using std::ostream;
using std::ofstream;
using std::ios;
template <class T> void writeToStream(ostream& o, T& val)
{
o.write(reinterpret_cast<char *>(&val), sizeof(T));
cout << o.tellp() << endl; //always outputs 4
}
struct foo {
uint16_t a, b;
};
int main()
{
foo myFoo = {42, 42};
ofstream test("test.txt", ios::binary);
writeToStream(test, myFoo);
// Just let the stream "test" pass out of scope.
// It closes automatically.
//test.close();
return 0;
}(我的标准库缺少cstdint,所以我使用了short而不是uint16_t,,但我怀疑这有什么关系。)
std::ofstream类型是从std::ostream派生的。如果传递一个普通的std::ostream,writeToStream()函数会更好,或者至少更规则、更通用。另外,对于信息:在C++中几乎不推荐使用using namespace std;。
祝好运。
https://stackoverflow.com/questions/9961064
复制相似问题