我需要创建一个将文件编码为base64的函数,并返回读取的字符数。 所以问题是当我遇到像ÿ这样的特殊字符时,我的当前代码会遇到问题,那么解决它的最简单方法是什么?
static void encodeblock( unsigned char *in, unsigned char *out, int len )
{
out[0] = encoding[ (int)(in[0] >> 2) ];
out[1] = encoding[ (int)(((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)) ];
out[2] = (len > 1 ? encoding[ (int)(((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6)) ] : '=');
out[3] = (len > 2 ? encoding[ (int)(in[2] & 0x3f) ] : '=');
}
int to_base64(const char *dst_file, const char *src_file)
{
unsigned char in[3];
unsigned char out[4];
int i, len, blocksout = 0;
int count = 0;
FILE *infile;
infile = fopen(src_file,"r");
if(infile==NULL){
return -1;
}
FILE *outfile;
outfile = fopen(dst_file,"w");
if(outfile==NULL){
return -1;
}
*in = 0;
*out = 0;
while( feof( infile ) == 0 ) {
len = 0;
for( i = 0; i < 3; i++ ) {
in[i] = fgetc(infile);
if(feof(infile) == 0 ) {
len++;
count+=1;
}
else {
in[i] = 0;
}
}
if( len > 0 ) {
encodeblock( in, out, len );
for( i = 0; i < 4; i++ ) {
putc( out[i], outfile );
}
blocksout++;
}
if( blocksout >= (64/4) || feof( infile ) != 0 ) {
if( blocksout > 0 ) {
fprintf( outfile, "\n" );
}
blocksout = 0;
}
}
fclose(infile);
fclose(outfile);
return( count );
}
答案 0 :(得分:0)
以二进制格式打开文件并访问