2010-11-19 32 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(); 
} 
相關問題