不知道什麼是錯的,也許你正在重複的內容。
變化是:
std::ofstream out(file, std::ios::binary | std::ios_base::app | std::ios_base::out);
到:
std::ofstream out(file, std::ios::binary);
,你應該罰款,如果你的字符串是好的。
檢查這個小例子:
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <vector>
using namespace std;
int main() {
string m_strReceivedMessage = "foo";
const char * c = m_strReceivedMessage.c_str();
ofstream out("test.bin", ios::binary);
int i = m_strReceivedMessage.size();
if (out.is_open()) {
out.write(c, i);
}
out.close();
ifstream input("test.bin", ios::binary);
// copies all data into buffer
vector<char> buffer((
istreambuf_iterator<char>(input)),
(istreambuf_iterator<char>()));
for(unsigned int i = 0; i < buffer.size(); ++i)
cout << buffer[i] << endl;
return 0;
}
,輸出:
[email protected]:~$ g++ -Wall px.cpp
[email protected]:~$ ./a.out
f
o
o
如需更多信息,請閱讀Reading and writing binary file。
這篇文章的縮進肯定會出錯,一開始。 :) – gsamaras
我不能從你的文章中分得很多。 「腐敗」是什麼意思?你期望寫什麼,寫什麼,以及你如何確定書面文件中的內容? – Roddy
m_strReceivedMessage有一些從pdf文件中讀取的二進制內容,它必須寫入另一個pdf文件中。但是在運行上述邏輯之後,當我嘗試打開輸出pdf文件時,它彈出一條錯誤消息「出現錯誤打開此文件。文件已損壞或無法修復「 –