我正在尝试以二进制模式编写和附加到文件但是文件如何被破坏。我无法理解它出错的地方,m_strReceivedMessage的类型是std :: string
const char * c = m_strReceivedMessage.c_str();
std::ofstream out(file, std::ios::binary | std::ios_base::app | std::ios_base::out);
int i = m_strReceivedMessage.size();
if (out.is_open()) {
out.write(c, i);
}
out.close();
答案 0 :(得分:1)
不确定是什么问题,也许你会重复内容。
改变:
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;
}
输出:
gsamaras@gsamaras-A15:~$ g++ -Wall px.cpp
gsamaras@gsamaras-A15:~$ ./a.out
f
o
o
有关详情,请阅读Reading and writing binary file。