#include <stdio.h>
#include <string.h>
#define TXTSIZE 76
char text[TXTSIZE];
char base64[(TXTSIZE - 1) / 3 * 4 + 2];
char list[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int count = 0;
int basecnt = 0;
char* base(char length){
if(!length)return NULL;
for(count = 0; count < length; count += 3){
basecnt = count / 3 * 4;
base64[basecnt] = list[(text[count] >> 2) & 0x3f];
base64[basecnt + 1] = list[(((text[count] & 0x03) << 4) & 0x30)|
(((text[count + 1] & 0xf0) >> 4) & 0x0f)];
base64[basecnt + 2] = list[(((text[count + 1] & 0x0f) << 2) & 0x3c)|
((text[count + 2] >> 6) & 0x03)];
base64[basecnt + 3] = list[text[count + 2] & 0x3f];
base64[basecnt + 4] = '\0';
}
switch(length % 3){
case 0:break;
case 1:base64[length/3*4 + 2] = base64[length/3*4 + 3] = '=';
case 2:base64[length/3*4 + 3] = '=';
default:break;
}
return base64;
}
int main(int argc, char* argv[]){
FILE *fp = NULL;
if(argc - 1){
fp = fopen(argv[1], "rb");
if(!fp){
printf("cannot open the file %s !\n", argv[1]);
return 1;
}
char outf[strlen(argv[1]) + 4 + 1];
sprintf(outf, "%s.b64", argv[1]);
FILE *fpo = NULL;
fpo = fopen(outf, "a+");
if(!fpo){
printf("cannot write to the file %s.b64 !\n", argv[1]);
return 1;
}
memset(text, 0, TXTSIZE);
fprintf(fpo, "------------------------------------------BEGIN BASE64CODE------------------------------------------\n");
while(base(fread(text, 1, TXTSIZE - 1, fp))){
fprintf(fpo, "%s\n", base64);
memset(text, 0, TXTSIZE);
}
fprintf(fpo, "-------------------------------------------END BASE64CODE-------------------------------------------\n");
fclose(fpo);
fclose(fp);
printf("base64 code has been saved into %s.b64\n", argv[1]);
return 0;
}
else{
memset(text, 0, TXTSIZE);
printf("Original text:");
scanf("%s", text);
}
printf("base64 code:%s\n", base(strlen(text)));
return 0;
}