如何在不reinterpret_cast的情况下将未签名的 char* 输出到文件

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

本文关键字:char 文件 输出 情况下 reinterpret cast      更新时间:2023-10-16

>我有一个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构造函数。您应该调用接受两个参数的参数 - char *和长度,而不是接受单个char *参数的参数。

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();