这是一个常见的问题,但我找不到合适的答案。
我有一个包含十六进制值的char数组。我需要在文本文件中“以字符串形式”写入此数组。
我对未存储在文件中的十六进制(理解为垃圾数据)的理解存在缺陷。在十六进制编辑器中,我可以看到数据。
我的十六进制数组实际上是整数数组,而不是字符。我需要考虑到这一点。
我尝试了这个:
FILE * out = fopen(out_file_name, "w");
char *in = (char*)malloc(sizeof(char) * num_encryption * 16);
....
fwrite(in, sizeof(char), num_encryption*16 + 1, out);
我也尝试过,stream
但它再次在文本文件中打印垃圾。
该in
数组包含以下十六进制字符串:21c169ea622e7d52ecd35423f4c3c9f4
,num_encryption=32
总共有32行()。
我也尝试过这样的事情:
std::ofstream outfile(argv[21]);
if(outtfile.is_open()){
//outtfile.write(wo, sizeof(char)*(num_encryption*16+1));
for(int k = 0; k < num_encryption; k++){
for(int j = 0; j < 16; ++j){
outfile << static_cast<unsigned char>(wo[j + k*16] & 0xff);
}
outtfile << std::endl;
}
}
甚至被注释的部分也无法正常工作。有什么建议么?
解决方案
我只是将输出(很好)重定向到文件:
FILE * out = fopen(out_file_name, "w");
for(int k = 0; k < num_encryption; k++){
for(int j = 0; j < 16; ++j){
fprintf(outfile, "%02x", wo[j + k*16] & 0xff);
}
fprintf(outfile, "\n");
}
fclose(outfile);
我不确定这是否是最优雅的解决方案,但是它对我有用。如果您知道的更好,请在此处添加。
如果问题也与C ++有关,那么让我为您提供有关如何使用C ++取代的功能的建议。您正在使用C样式的功能。
您应该使用iostream。避免使用malloc,使用new,但更好的是使用avector<char>
或unique_ptr<char[]>
直接使用。在这种情况下,我将使用unique_ptr<char[]>
它,因为似乎您无需调整数组的大小。我假设您想在下面编写一个二进制文件。
//I assume you want a binary file
std::ostream file("myfile.txt", std::ios::binary);
std::unique_ptr<char []> in = std::unique_ptr<char []>(new char[num_encryption * 16]);
if (file)
file.write(in.get(), sizeof(char) * num_encryption * 16);
如果需要,可以用十六进制写入文本数据,请以文本模式打开文件:
std::ostream file("myfile.txt"); //Note, no std::ios::binary
...
file >> std::hex >> std::noshowbase; //Write in hex with no base
std::copy(in.get(),
in.get() + num_encryption * 16,
std::ostream_iterator<char>(file)); //Write one char at a time, in hex, with no base
警告:未经测试,仅显示了如何按char写入二进制或格式化的十六进制文本的想法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句