I am trying to write some simple program to uploading files to my server. I’ d like to convert binary files to hex. I have written something, but it does not work properly.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static int bufferSize = 1024;
FILE *source;
FILE *dest;
int n;
int counter;
int main() {
unsigned char buffer[bufferSize];
source = fopen("server.pdf", "rb");
if (source) {
dest = fopen("file_test", "wb");
while (!feof(source)) {
n = fread(buffer, 1, bufferSize, source);
counter += n;
strtol(buffer, NULL, 2);
fwrite(buffer, 1, n, dest);
}
}
else {
printf("Error");
}
fclose(source);
fclose(dest);
}
I use strtol to convert binary do hex. After invoking this code I have still strange characters in my file_test file.
I’ d like to upload a file on server, for example a PDF file. But firstly I have to write a program, that will convert this file to a hex file. I’d like that the length of a line in hex file would be equal 1024. After that, I will upload this file line by line with PL/SQL.
Your code is fantastically confused.
It’s reading in the data, then doing a
strtol()call on it, with a base of 2, and then ignoring the return value. What’s the point in that?To convert the first loaded byte of data to hexadecimal string, you should probably use something like:
Then write
hexto the output file. You need to do this for all bytes loaded, of course, not justbuffer[0].Also, as a minor point, you can’t call
feof()before you’ve tried reading the file. It’s better to not usefeof()and instead check the return value offread()to detect when it fails.