对STL字符串使用fread/fwrite.这是正确的吗? [英] Using fread/fwrite for STL string. Is it correct?

查看:64
本文介绍了对STL字符串使用fread/fwrite.这是正确的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含字符串的结构.像这样的东西:

I have a structure, that contain string. Something like that:

struct Chunk { int a; string b; int c; };

struct Chunk { int a; string b; int c; };

因此,我想我无法使用fread和fwrite函数从文件写入和读取此结构.因为字符串可能保留不同的存储容量. 但是这样的代码可以正常工作.

So, i suppose, that i cannot write and read this structure from file using fread and fwrite functions. Because string may reserve different memory capacity. But such code works correctly.

Chunk var;

fwrite(&var, sizeof(Chunk), 1, file);

fread(&var, sizeof(Chunk), 1, file);

其中确实存在一些问题吗?

Is there really some problems in it?

推荐答案

您对此表示怀疑.您只能流式传输fwritefread的POD类型,而string不是POD.

You are justified in doubting this. You should only stream POD types with fwrite and fread and string is not POD.

这篇关于对STL字符串使用fread/fwrite.这是正确的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆