2010-11-19 97 views

回答

3

好吧,如果你想与二进制文件工作,你可以使用普通的C API(FOPEN/FREAD/FWRITE/FCLOSE)或查找C++的库:的iostream和fstream的

1

检查标准iostream的使用和fstream类。使用C API是可惜的,但仍然有可能。

0

快速回答:没有。

回应其他答案: 标准模板库提供了用于流式传输数据的类,但不提供任何高级功能来将数据转换为序列化二进制格式并返回。

< <和>>运算符可以为显式编写代码以支持它们的类工作。但是这并不像BinaryWriter和BinaryReader能够做到的那样,这就是流式传输整个对象图,并将循环引用考虑在内。在.NET中,所有需要的就是每个类都具有[Serializable]属性适用于他们。

如果您想了解C++和C#之间的差异,您可以理解为什么不提供完整的二进制格式化程序。我能想到的问题是

  • C++没有C#的反射功能。
  • 由于C++没有托管内存,考虑到循环引用,不可能流式传输对象图形。
+0

STD::(I | O)流是字节流。操作员<< and >>是与“toString反射”有关的。 – Artyom 2010-11-19 10:56:13

+0

@Artyom - std :: iostreams提供了一种流式序列化数据的方式。它并没有帮助将对象图转换为序列化数据。 – 2010-11-19 11:04:58

-1

与C#不同的是,字符串是两个字节“字”的序列并编码为UTF-16。 C++字符串(std :: string)是字节序列,它们通常使用UTF-8或其他本地编码进行编码,具体取决于您的系统。

因此,当您向“字节流”写入字符串时,没有字符集转换,因此像std :: fstream或内存流一样的普通文件流(如std :: stringstreadm)都源自std :: ostream,并且/或std :: istream,实际上是您正在查找的字节流。

+1

C#二进制格式化程序可以格式化任何对象,而不仅仅是字符串。 – 2010-11-19 11:09:34

+0

@Andrew Shepherd - 如果他们以合理的方式实现ToString()...如果实现了'operator <<',它可以用同样的方法来格式化任何C++对象。 – Artyom 2010-11-19 13:06:20

0

你只需要一个库:boost::serialization

3

你可以得到的最接近的是与ofstreamifstream类:

// Write an integer, a double and a string to a binary file using ofstream 
std::ofstream out("out.data", std::ios_base::out | std::ios_base::binary); 
out << 10 << ' ' << 893.322 << ' ' << "hello, world" << std::endl; 
out.close(); 

// Read an integer, a double and a string from a binary file using ifstream: 
std::ifstream in("in.data", std::ios_base::in | std::ios_base::binary); 
int i = 0; 
double d = 0.0f; 
std::string s; 
in >> i; 
in >> d; 
in >> s; // reads up to a whitespace. 

// or you can read the entire file in one shot: 
std::stringstream buffer; 
buffer << in.rdbuf(); 
s = buffer.str(); // the entire file contents as an array of bytes. 

in.close(); 
+0

+1例如,当我们大多数人只是链接在。 – 2010-11-19 11:44:51

+2

BinaryWriter等写入数据作为二进制数据,所以如果你输出一个int你得到的int的字节。这将它们转换为一个字符串。 ios_base:binary只是告诉流不要转换行尾字符,它不会做我怀疑原始海报想要的东西。 – jcoder 2010-11-19 13:15:35

1

你必须以二进制方式来打开的fstream,然后使用读取和编写函数来执行二进制读取和写入。

事情是这样的 -

#include <fstream> 
int main() 
{ 
    std::ofstream out("out.data", std::ios_base::out | std::ios_base::binary); 

    int a = 120; 
    out.write(reinterpret_cast<const char*>(&a), sizeof(int)); 
    out.close(); 
}