This is a frequently question but I could not find appropriate answer.
I have a char array containing HEX values. I need to write this array in a text file "as a string".
My understanding of HEX not being stored in the files (looked garbage data) was flawed. In Hex editor I could see the data.
My Hex array is actually integer array and not characters. This I need to take into consideration.
I tried this:
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);
I also tried stream but it again prints garbage in text files.
The in array contains the HEX strings like this: 21c169ea622e7d52ecd35423f4c3c9f4, and there are 32 lines (num_encryption=32) in total.
I also tried something like this:
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;
}
}
Even the commented part did not work properly. Any suggestions?
Solution
I just redirected the output (which was fine) to the file:
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);
I am not sure if this is the most elegant solution,but it works for me. If you know anything better then please add here.
inarray by actual int value? And what values you hope to output? For example if you have a int value of 15 in your byte array, are you expecting to see an ASCII 'F' (int 70) in the out? If so, you need to convert...fwritegenerally won't give you a text file, it moves binary data around.chararray being used to hold actual character values (like'2') or integer values (like2)? That's fundamental difference is rather important to figuring out the problem and the solution. The fact that you show a string of 32 characters but then say a line is 16 bytes rather suggests integers. Try opening your "garbage" text file in a hex editor and see if you've ended up outputting data as raw integer values instead of characters.