如何在没有 reinterpret_cast 的情况下将 unsigned char* 输出到文件

How do I output an unsigned char* to file without reinterpret_cast

我有一个 unsigned char* 填充字符,而不仅仅是 ASCII 例如:`

¤ÝkGòd–ùë$}ôKÿUãšj@Äö5ÕnE„_–Ċ畧-ö—RS^HÌVÄ¥U`  . 

如果我reinterpret_cast,如果我没记错的话我会丢失字符,因为它们不全是 ASCII。我到处搜索,但所有解决方案都需要某种会改变数据的转换或转换。这是我有的,但不起作用。

unsigned char* cipherText = cipher->encrypt(stringTest);
string cipherString(reinterpret_cast<char*>(cipherText));  //<-- At this point data changes in debugger
outputfile.open(outfile);       
outputfile.close();             

您没有呼叫您应该呼叫的 string constructor。而不是采用单个 char * 参数的参数,您应该调用采用两个参数的参数 - char * 和 length.

basic_string( const CharT* s,
              size_type count,
              const Allocator& alloc = Allocator() );

在你的例子中使用它

unsigned char* cipherText = cipher->encrypt(stringTest);
size_t cipherTextLength = // retrieve this however the API allows you to
string cipherString(reinterpret_cast<char*>(cipherText), cipherTextLength);

outputfile.open(outfile);       
// assuming outputfile is an ofstream
outputfile << cipherString;
outputfile.close();  

请注意,调试器可能仍指示截断的字符串,具体取决于它如何解释 string 的内容。如果您在编辑器中打开输出文件并检查字节,您应该会看到预期的结果。

正如 RemyLebeau 在评论中提到的,如果您不需要 std::string 用于任何其他目的,您甚至不需要创建它,只需写信给 ofstream直接。

outputfile.open(outfile);       
outputfile.write(reinterpret_cast<char*>(cipherText), cipherTextLength);
outputfile.close();