0
我在C++中编写了一个二进制文件,下面的代码。它输出文件,但是当我打开它。我看到它是一种ASCII格式。我究竟做错了什么 ?如何将字符串消息保存为二进制文件?写入二进制C++错误
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
using std::ios;
void writeFile(const std::string &fileName, const std::string data)
{
std::ofstream ofs;
ofs.open(fileName.c_str(), ios::out | ios::binary);
if (ofs.is_open())
{
ofs.write(data.c_str(),data.size());
ofs.close();
}
else
{
std::cerr <<"Error while writing File: "<<fileName<<std::endl;
exit (EXIT_FAILURE);
}
}
int main(int argc, char const *argv[])
{
/* code */
std::string message = "This should be binary";
writeFile("sample", message);
return 0;
}
你知道如何将ascii字符串写成二进制文件吗?那么它是否也需要在阅读时重新转换为字符串? – itsnevertoobadtoaskforhelp
@itsnevertoobadtoaskforhelp:你已经做到了。字符串的字面字节存储在文件中。关键是字面字节是ASCII文本,所以它看起来像文本。重读ShadowRanger的答案。 –