这是在二进制文件中写入字符串的一段代码:
std::string s("Hello");
unsigned int N(s.size());
fwrite(&N,sizeof(N), 1 ,bfile);
fwrite(s.c_str(),1, N ,bfile);
fflush(bfile);
读取字符串的片段:
std::string new_s("");
unsigned int N(0);
fread(&N,sizeof(N),1,bfile);
char* c(new char[N+1]);
fread(c,1,N,bfile);
c[N] = '\0';
new_s = c;
delete[] c;
问题:
- 有更简单的方法吗?
- 当我写/读文件时,我应该考虑空字符
'\0'
吗?来自c_str()
?
我有一个与 char* c(new char[N])
有关的附带问题:
- 我知道 C++ 不允许创建静态数组,例如 int
a[size_of_array]
, 所以解决方案是使用由new[]
创建的指针并用delete[]
删除.这是唯一的解决方案吗(如果我不能使用std::vector < int >
),这个解决方案是否有效?
最佳答案
首先,std::string::size()
不考虑 NUL 字符,因此您的二进制文件将不包含该字符。您的序列化策略很好(首先是大小,然后是字符集。)
至于读取,最好使用vector
(在c++03中,或在c++11中直接使用string
)。
因此,一旦您确定了大小 (N
),那么:
std::vector<char> content(N, 0); // substitute std::string if possible
fread(&content[0],1,N,bfile);
// Construct the string (skip this, if you read into the string directly)
std::string s(content.begin(), content.end());
关于字符串的 C++ fwrite 和 fread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15366073/