#include #include "dk4rle.h" #include "dk4edstm.h" $!trace-include /* Example file for run-length encoding. The program reads data from standard input, applies run-length encoding and writes result data to standard output. For better understanding we only do minimal diagnostics here (set exit status code). In real world programs one would issue more diagnostics on problems. */ int main(int argc, char *argv[]) { dk4_rl_enc_t enc; /* Encoder */ const unsigned char *ucptr; /* Address of output buffer */ unsigned long offset; /* Current offset in file */ size_t sz; /* Number of output characters */ size_t i; /* Current output char index */ #if DK4_ON_WINDOWS int oldimode; /* Old file mode for stdin */ int oldomode; /* Old file mode for stdout */ #endif int ic; /* Current input char from stdin */ int exval = 0; /* Exit status code */ $!trace-init test-rle.deb $? "+ main" /* On Windows we must set stdin and stdout to binary mode explicitly. */ #if DK4_ON_WINDOWS oldimode = _setmode(_fileno(stdin), _O_BINARY); oldomode = _setmode(_fileno(stdout), _O_BINARY); #endif /* Initialize encoder. */ dk4rle_init(&enc, 0, NULL); $? ". initialized" $? ". enc->iused = %u", (unsigned)(enc.iused) /* Process standard input. */ offset = 0UL; while (EOF != (ic = fgetc(stdin))) { $? ". new char, offset = %lu %lx", offset, offset switch (dk4rle_add(&enc, (unsigned char)ic, NULL)) { case DK4_EDSTM_FINISHED : { $? ". must retrieve output" ucptr = NULL; sz = 0; if (0 != dk4rle_output(&ucptr, &sz, &enc, NULL)) { $? ". output" if ((NULL != ucptr) && (0 < sz)) { $? ". pointers" $? ". write %u bytes", (unsigned)sz for (i = 0; i < sz; i++) { $? ". fputc %u = %02x", (unsigned)i, (unsigned)(ucptr[i]) if (EOF == fputc((int)(ucptr[i]), stdout)) { $? "! EOF" exval = 1; } } } } } break; case DK4_EDSTM_ERROR : { $? ". error" exval = 1; } break; default : { $? ". no action required" } break; } offset++; } $? ". all input processed" /* If successful so far, process final data from encoder. */ if (0 == exval) { $? ". finish" switch (dk4rle_finish(&enc, NULL)) { case DK4_EDSTM_FINISHED : { $? ". output" ucptr = NULL; sz = 0; if (0 != dk4rle_output(&ucptr, &sz, &enc, NULL)) { if ((NULL != ucptr) && (0 < sz)) { $? ". write %u bytes", (unsigned)sz for (i = 0; i < sz; i++) { $? ". fputc %u %02x", (unsigned)i, (unsigned)(ucptr[i]) if (EOF == fputc((int)(ucptr[i]), stdout)) { exval = 1; } } } } } break; case DK4_EDSTM_ERROR : { $? "! error" exval = 1; } break; default : { $? ". no action required" } break; } } /* Restore previous file mode for stdin and stdout on Windows. */ #if DK4_ON_WINDOWS fflush(stdout); _setmode(_fileno(stdout), oldomode); _setmode(_fileno(stdin), oldimode); #endif /* Exit, indicate success or error. */ $? "- main %d", exval $!trace-end exit(exval); return exval; }