簡體   English   中英

使用<<運算符將二進制文件寫入std :: fstream

[英]Writing binary to std::fstream using the << operator

由於某種原因,此排序代碼無法正常工作:

std::fstream theFile;
theFile.open(<someFilename>, std::ios::beg |std::ios::out|std::ios::binary|std::ios::trunc);
theFile << 1;          //1 is being written as a string
int var= 25;

theFile << 25;        //same thing, 25 is written as a string

可能是什么問題呢? 我正在使用Visual Studio 2010附帶的Microsoft C ++編譯器。

<<運算符的整個目的是將格式化數據寫入流。 如果要編寫二進制數據,則應使用ostream::write()ostream::put()

您需要首先將值作為char進行類型轉換,否則iostream庫會將值視為int並將它們格式化為可讀字符串。

theFile << (char)1 << (char)25;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM