如何在不reinterpret_cast的情况下将未签名的 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
构造函数。您应该调用接受两个参数的参数 - 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();
相关文章:
- 将 boost::文件系统::p ath 转换为 char?
- 为什么当我尝试将char输入到int时,文件指针会卡住
- 从带有 std::ifstream::read() 的文件中读取 int 遍历 char * 二进制数据
- 将.txt文件存储到 char* 2d 矢量C++中
- 将文本文件读取为 const char* 有时有效,有时无效
- C 通过char读取文件字符串的文件char;崩溃
- 如何通过C 读取CHAR的文件字符
- C 如何读取从文件到char数组的文本行
- 如何使用 C++ 中的写入函数将浮点转换为 char 以写入文件
- 如何修复此 OpenCV 错误:断言失败((无符号)i < (无符号)cn) 在 cv::Vec<unsigned char,3>:::运算符 (), 文件
- C 字符串到C char数组,以写入二进制文件
- 为什么使用char数组来存储以二进制模式打开的文件的内容
- 如何将足够的数据从文本文件分配到char*中,然后将其复制到内存C 中
- 想要在读取文件时在类型的char上使用atoi()
- 在 c++ 中将整个.txt文件复制到 char 数组中
- 从一个文本文件加载多个 char 和 int 类型的数组
- C :如何以快速方式读取Char文件
- C++ 中的文件处理错误 - 调用"std::basic_fstream<char, std::char_traits<char> >::open(const char[8],
- 从文本文件读取到 char* 数组
- 在C++中读取二进制文件时将char*转换为double