如何将字符串作为二进制文件写入文件? [英] How to write strings as binaries to file?

查看:198
本文介绍了如何将字符串作为二进制文件写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个C ++问题。我有一个类包含一个字符串:

  class MyClass {
public:
std :: string s;
};

我有一个MyClass对象数组:

  MyClass * array = MyClass [3]; 

现在我想将数组作为二进制写入文件。我不能使用:

  Ofstream.write((char *)array,3 * sizeof(MyClass))



因为MyClass的大小不同。



Ofstream.write实现的目的?非常感谢。

解决方案

在C ++中,通常使用 BOOST序列化类



以编程方式您可以这样做:



写作:

 
std :: ofstream ostream(myclass.bin,std :: ios :: binary);
if(!ostream)返回; //错误!
std :: size_t array_size = 3;
ostream.write(reinterpret_cast< char *>(&array_size),sizeof(std :: size_t));
for(MyClass * it = array; it!= array + array_size; ++ it)
{
MyClass&mc = * it;
std :: size_t s = mc.s.size();
ostream.write(reinterpret_cast< char *>(&s),sizeof(std :: size_t));
ostream.write(mc.s.c_str(),s.size());
}

阅读

 
std :: ifstream istream(myclass.bin,std :: ios :: binary);
if(!istream)return; //错误!
std :: size_t array_size = 0;
istream.read(reinterpret_cast< char *>(&array_size),sizeof(std :: size_t));
array = new MyClass [array_size];
for(MyClass * it = array; it!= array + array_size; ++ it)
{
MyClass&mc = * it;
std :: size_t s;
istream.read(reinterpret_cast< char *>(&s),sizeof(std :: size_t));
mc.resize(s);
istream.read(mc.s.c_str(),s.size());
}
istream.close(); //不需要,因为范围应该关闭神奇的


This is a C++ question. I have a class that contains a string:

class MyClass{
public:
std::string s;
};

And I have an array of MyClass objects:

MyClass * array = MyClass[3];

Now I want to write the array as binaries into a file. I cannot use:

Ofstream.write((char *)array, 3 * sizeof(MyClass))

because the size of MyClass varies.

How can I use Ofstream.write to achieve the purpose? Many thanks.

解决方案

In C++ it is usually done using the BOOST serialization class

Programmatically you could do something like this:

Writing:

std::ofstream ostream("myclass.bin",std::ios::binary);
if (!ostream) return; // error!
std::size_t array_size = 3;
ostream.write(reinterpret_cast<char*>(&array_size),sizeof(std::size_t));
for(MyClass* it = array; it != array + array_size; ++it)
{
  MyClass& mc = *it;
  std::size_t s = mc.s.size();
  ostream.write(reinterpret_cast<char*>(&s),sizeof(std::size_t));
  ostream.write(mc.s.c_str(),s.size());
}

Reading

std::ifstream istream("myclass.bin",std::ios::binary);
if (!istream) return; // error!
std::size_t array_size = 0;
istream.read(reinterpret_cast<char*>(&array_size),sizeof(std::size_t));
array = new MyClass[array_size];
for(MyClass* it = array; it != array + array_size; ++it)
{
  MyClass& mc = *it;
  std::size_t s;
  istream.read(reinterpret_cast<char*>(&s),sizeof(std::size_t));
  mc.resize(s);
  istream.read(mc.s.c_str(),s.size());
}
istream.close(); // not needed as should close magically due to scope

这篇关于如何将字符串作为二进制文件写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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