【发布时间】:2014-10-31 02:02:23
【问题描述】:
好的,所以我这里有点问题。
我正在做的是将二进制文件(在此示例中我使用 .exe 文件)转换为 Base64 字符串,然后将其转换回二进制数据以将其写入磁盘。
到目前为止一切顺利,这段代码有效:
std::string str = base64_decode(base64str); // base64str is the base64 string made of the actual .exe file
std::ofstream strm("file.exe", std::ios::binary);
strm << str;
strm.close();
文件“file.exe”正在按预期创建,我可以运行它。
现在我的问题是我需要解密文件作为 char* 而不是 std::string,但是每当我调用此代码时
str.c_str();
要将其转换为 const char* 或 char*,内容突然不再等于 str 中包含的二进制数据,而是这样:
MZP
所以,比如下面的代码
std::string str = base64_decode(base64str);
std::ofstream strm("file.exe", std::ios::binary);
char* cstr = new char[str.length()-1];
strcpy(cstr, str.c_str());
strm << cstr;
strm.close();
将创建 file.exe,但这次它将包含“MZP”而不是实际的二进制数据
我不知道如何解决这个问题。当然 char* 是强制性的。
你们可以帮忙吗?
【问题讨论】:
-
strcpy(cstr, str.c_str());将在遇到第一个空字节后停止复制,您的二进制文件中可能有数百个空字节。 -
不要使用
strm << cstr,它将在第一个空值处停止。使用strm.write()。