#include #include #include #include #include #include #include #include #include #define CHUNK 16384 #define CHUNK_IN CHUNK #define CHUNK_OUT (CHUNK_IN << 1) /* Ensure enough output space */ void usage(char *args[]) { printf("usage: %s [-h|--help] [] []\n", args[0]); exit(0); } void print_err(const char *msg) { fprintf(stderr, "error: %s", msg); } int encode(FILE *source, FILE *dest) { int ret, eof; uint available; soleg_stream strm; unsigned char in[CHUNK_IN]; unsigned char out[CHUNK_OUT]; ret = soleg_stream_init(&strm); if (ret != SOLEG_OK) { print_err("Init failed\n"); return ret; } do { strm.avail_in = fread(in, 1, CHUNK_IN, source); if (ferror(source)) { print_err("Could not read input!\n"); return SOLEG_ERRNO; } eof = feof(source); strm.inp = in; strm.avail_out = CHUNK_OUT; strm.outp = out; ret = soleg_encode(&strm); if (ret != 0) { print_err("Could not encode\n"); return ret; } /* Consume encoded values */ if (!eof) { available = CHUNK_OUT - strm.avail_out; if (fwrite(out, 1, available, dest) != available || ferror(dest)) { print_err("Writing output"); return SOLEG_ERRNO; } } } while (!eof); soleg_encode_end(&strm); available = CHUNK_OUT - strm.avail_out; if (fwrite(out, 1, available, dest) != available || ferror(dest)) { print_err("Writing output"); return SOLEG_ERRNO; } /* Missing encoded EOF */ soleg_stream_free(&strm); return SOLEG_OK; } int main(int argc, char *argv[]) { if (argc == 1) return encode(stdin, stdout); if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) usage(argv); int i = 1; FILE *source = stdin; if (argc > i) { source = fopen(argv[i], "rb"); if (source == NULL) { printf("Could not open file '%s'\n", argv[i]); return 1; } } FILE *dest = stdout; if (argc > ++i) { dest = fopen(argv[i], "wb"); if (dest == NULL) { printf("error: Could not open '%s'.\n", argv[i]); return 1; } } int ret = encode(source, dest); fclose(source); fclose(dest); return ret; }