首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ostream::write not write整个struct?

ostream::write not write整个struct?
EN

Stack Overflow用户
提问于 2012-04-01 09:03:04
回答 2查看 185关注 0票数 1

我正在尝试将各种值导出到一个二进制文件中,比如int和简单的struct。下面是一些代码:

代码语言:javascript
复制
#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.amyFoo.b更改为包含256或更大的值(需要存储超过1个字节),则文件将变为4字节长。我在Win7上使用Visual Studio11开发人员预览版;我还没有检查其他系统或编译器上是否也发生了同样的事情。对于a或b低于256的值,如何使其正确输出?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-01 09:11:54

文件只能由理解其存储格式的程序回读。Notepad++无法理解您的文件的存储格式,因此它无法读回文件并正确地呈现它。要么以Notepad++理解的格式写入文件,例如ASCII文本,要么仅使用能够理解您编写的格式的程序读取文件。

票数 2
EN

Stack Overflow用户

发布于 2012-04-01 09:23:37

我清理了你的代码,如下所示。虽然我不知道为什么旧代码输出两个字节,但新代码确实输出了四个字节。

代码语言:javascript
复制
#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::ostreamwriteToStream()函数会更好,或者至少更规则、更通用。另外,对于信息:在C++中几乎不推荐使用using namespace std;

祝好运。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9961064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档