In my program, I am trying to read data from binary file, and then write it’s hex representation to txt file.
#include <stdio.h>
#include <stdlib.h>
int counter = 0;
int read;
int i = 0;
long size;
FILE *file1 = NULL;
FILE *file2 = NULL;
fpos_t length;
char newLine = '\n';
int main(int argc, char **argv) {
if (argc < 2) {
printf("Use: %s file1 file2", argv[0]);
exit (-1);
}
unsigned char hex[513];
unsigned char buffer[257];
file1 = fopen(argv[1], "rb");
fseek(file1, 0, SEEK_END);
fgetpos(file1, &length);
size = length.__pos;
fseek(file1, 0, SEEK_SET);
if (file1) {
file2 = fopen(argv[2], "w");
if (!file2) {
printf("Cannot open file: %s\n", argv[2]);
exit(-1);
}
while (counter < size) {
read = fread(buffer, 1, 256, file1);
counter += read;
i = 0;
while (i < read) {
sprintf(hex, "%02x", buffer[i++]);
}
fwrite(hex, 1, 512, file2);
fwrite(&newLine, 1, 1, file2);
}
} else
printf("Cannot open file %s\n", argv[1]);
fclose(file1);
fclose(file2);
}
Unfortunately data don’t write to txt file properly. Please help me find my mistake. What is wrong in this code?
Part of the issue is that the
sprintfcall will keep overwriting whatever is inhex. It does not append to it. So the result is that it writes the full size of that buffer to the file, but it will only have the very last hex value in it (in the first 2 bytes).