对STL字符串使用fread/fwrite.这是正确的吗? [英] Using fread/fwrite for STL string. Is it correct?
问题描述
我有一个包含字符串的结构.像这样的东西:
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?
推荐答案
您对此表示怀疑.您只能流式传输fwrite
和fread
的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屋!