バイナリファイルを書き込むために、以下のコードを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の答えを再読み込みします。 –