字符串的 C++ fwrite 和 fread

标签 c++ arrays string fwrite fread

这是在二进制文件中写入字符串的一段代码:

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/

相关文章:

c++ - 分配在 "stack"上的 vector 可以在函数之间传递吗?

c++ - 是否可以出于性能目的创建默认初始化的类 std::is_trivial

C++如何使用CWnd *对象加载图片?

c# - 将 outlook rtfbody 添加到包含其图像的 richtextbox

C++ 未定义的函数引用

c++ - CUDA:将统一内存与类和数组一起使用

php - 需要把mysql的数据以某种格式打印成json

C#:去掉字符串中的多个无效字符

Java 如何获得 HH :mm:ss from Date

C# 4.0 如何获取给定字符串的 64 位哈希码