Posted By

Zydeco on 10/11/09


Tagged

length run RLE runlength run-length


Versions (?)

RLE Encoding and decoding


 / Published in: C
 

URL: http://en.wikipedia.org/wiki/Run-length_encoding

Encode and decode RLE from files

  1. int rle_encode_file (FILE * in, FILE * out)
  2. {
  3. int block_len, block_char, c;
  4. block_len = 0;
  5. block_char = -1;
  6.  
  7. for(;;)
  8. {
  9. c = getc(in);
  10. if (c == EOF) break;
  11.  
  12. if (c == block_char && block_len < 255)
  13. {
  14. /* same block */
  15. block_len++;
  16. }
  17. else
  18. {
  19. if (block_len)
  20. { /* write block */
  21. putc(block_len, out);
  22. putc(block_char, out);
  23. }
  24. /* start new block */
  25. block_len = 1;
  26. block_char = c;
  27. }
  28. }
  29.  
  30. if (block_len)
  31. {
  32. /* last block */
  33. putc(block_len, out);
  34. putc(block_char, out);
  35. }
  36. return 1;
  37. }
  38.  
  39. int rle_decode_file (FILE * in, FILE * out)
  40. {
  41. int i, len, c;
  42.  
  43. for(;;)
  44. {
  45. len = getc(in); /* block length */
  46. c = getc(in); /* character */
  47.  
  48. /* checking */
  49. if (len == EOF) return 1; /* end of file */
  50. if (c == EOF) return 0; /* bad format */
  51.  
  52. /* output */
  53. for(i = 0; i < len; i++) putc(c, out);
  54. }
  55. }

Report this snippet  

You need to login to post a comment.