用base64编码二进制数据替换fread?

时间:2019-05-03 07:54:28

标签: c base64

需要有关我的C的帮助,已经太久了,试图使这个小脚本正常工作。

我已经包含了base64 library from here

我将二进制文件数据编码为base64字符串。

并且基本上是尝试将数据从base64编码的字符串中馈送到函数中,而不是使用fread。同样,base64编码的字符串也很大(500k至一百万个字符)。

#include "base64.h"

...

static int _process()
{
    byte_t  daata[2048]        = {0};
    size_t int1                = 2048;
    size_t int2                = 2048;
    unsigned char s1[10000000] = "dGVzdGluZzEyMw==";

    printf("%s", s1);

    // TODO: Not sure how to call this properly.
    base64_decode(s1, int1, int2);

    // TODO: Replace this with data from base64 decoded char rather than file.
    read_size = fread(data, sizeof(char), 2048, p_file);

    while (read_size > 0)
    {
        write_data(
            handle,
            data,
            read_size
        );

        // TODO: Continue reading until string is empty?
        read_size = fread(data, sizeof(char), 2048, p_file);
    }
}

1 个答案:

答案 0 :(得分:0)

如果您担心文件的大小,大概是将整个内容立即存储到内存中,则必须

  1. 读取输入文件的一部分
  2. 解码块
  3. 将解码后的数据写到输出文件中

循环播放,直到完成阅读为止。这样一来,您一次只能在内存中处理一个块。请注意,在implementation中,您有责任删除base64_decode给您的内容。每次都会为您分配一些东西。

大约...

size_t chunk_size = 2048;
size_t read_size = 0;
size_t write_size = 0;
unsigned char* encoded_data = malloc(sizeof(unsigned char) * chunk_size);

//...open input file and output file...
read_size = fread(encoded_data, sizeof(unsigned char), chunk_size, input_file);
while (read_size > 0)
{
    unsigned char* decoded_data = base64_decode(encoded_data, read_size, &write_size);
    fwrite(decoded_data, sizeof(unsigned char), write_size, output_file);
    free(decoded_data);
    read_size = fread(encoded_data, sizeof(unsigned char), chunk_size, input_file);
}
//...close files

free(encoded_data);