Base64 is a widely used encoding mechanism to allow arbitrary binary content to be transferred as printable text. This program is designed to take binary file as input and produce a Base64-encoded binary file as output.
#include <stdlib.h>
#include <stdio.h>
void enblock( int len, char *in, char *base64, FILE *outputFILE)
{
fprintf(outputFILE, "%c", base64[in[0] >> 2]);
fprintf(outputFILE, "%c", base64[((in[0] & 3) << 4) | ((in[1] & 240) >> 4)]);
if (len > 1)
{
fprintf(outputFILE,"%c", base64[((in[1] & 15) << 2) | ((in[2] & 192) >> 6)]);
}
else
{
fprintf(outputFILE, "%c", '=');
}
if (len > 2)
{
fprintf(outputFILE, "%c", base64[(in[2] & 63)]);
}
else
{
fprintf(outputFILE, "%c",'=');
}
}
void endecode (FILE *inputFILE, FILE *outputFILE)
{
static char base64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int len = 0;
int i = 0;
char buffer[3] = {0};
while ((len = fread(buffer,sizeof(char),3,inputFILE)) >= 1)
{
for (i = len; i < 3; i++)
buffer[i] = 0;
enblock(len, buffer, base64 ,outputFILE );
}
}
int main()
{
FILE *file1 = NULL;
FILE *file2 = NULL;
if (NULL == (file1 = fopen("INPUT.txt", "r")))
{
printf("Can't open INPUT file!");
return -1;
}
if (NULL == (file2 = fopen("OUTPUT.base64", "wb")))
{
printf("Can't create OUTPUT file");
return -1;
}
endecode(file1,file2);
fclose(file1);
fclose(file2);
return 0;
}
if (NULL != (file1 = fopen("INPUT.txt", "r")))
? I also always put the assignment/function calls first. – Goswin von Brederlow Nov 23 '14 at 21:05