Guest User

Untitled

a guest
Apr 20th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. #include "stdio.h"
  2.  
  3. #define MAX_REP 255
  4.  
  5. void rle_compress(char *infile, char *outfile) {
  6. FILE *inf = fopen(infile, "rb");
  7. FILE *outf = fopen(outfile, "wb");
  8.  
  9. char prevChar = 0, currChar = 0;
  10. bool first = true, rep = false;
  11. unsigned char repCount = 0;
  12.  
  13. while (fread(&currChar, sizeof(char), 1, inf)) {
  14. if (!rep)
  15. fwrite(&currChar, sizeof(char), 1, outf);
  16. if (first) {
  17. first = false;
  18. } else {
  19. if (prevChar == currChar) {
  20. if (!rep) {
  21. rep = true;
  22. repCount = 2;
  23. } else {
  24. repCount++;
  25. if (repCount == MAX_REP) {
  26. fwrite(&repCount, sizeof(unsigned char), 1, outf);
  27. rep = false;
  28. repCount = 0;
  29. first = true;
  30. }
  31. }
  32. } else {
  33. if (rep) {
  34. fwrite(&repCount, sizeof(unsigned char), 1, outf);
  35. rep = false;
  36. repCount = 0;
  37. fwrite(&currChar, sizeof(char), 1, outf);
  38. }
  39. }
  40. }
  41. prevChar = currChar;
  42. }
  43.  
  44. rep && fwrite(&repCount, sizeof(unsigned char), 1, outf);
  45. fclose(outf);
  46. fclose(inf);
  47. }
  48.  
  49. void rle_decompress(char *infile, char *outfile)
  50. {
  51. FILE *inf = fopen(infile, "rb");
  52. FILE *outf = fopen(outfile, "wb");
  53.  
  54. unsigned char prevChar = 0, currChar = 0;
  55. bool rep = false, passOne = false;
  56. size_t rd;
  57. while (!feof(inf))
  58. {
  59. rd = fread(&currChar, sizeof(currChar), 1, inf);
  60. if (rd == 0)
  61. break;
  62. if (rep)
  63. {
  64. for (int i = 0; i < currChar - 2; i++)
  65. fwrite(&prevChar, sizeof(prevChar), 1, outf);
  66. rep = false;
  67. passOne = true;
  68. }
  69. else
  70. {
  71. fwrite(&currChar, sizeof(currChar), 1, outf);
  72. if (passOne)
  73. passOne = false;
  74. else if (currChar == prevChar)
  75. rep = true;
  76. }
  77. prevChar = currChar;
  78. }
  79. fclose(outf);
  80. fclose(inf);
  81. }
  82.  
  83. int main(int argc, char *argv[])
  84. {
  85. if (argc != 2)
  86. {
  87. printf("RLE Compressor by Gorodilova Love\nUsage:\n");
  88. printf("\trle.exe <c|d>\nwhere\n");
  89. printf("\t<c|d> - c - for compression, d - for decompression\n");
  90. return 0;
  91. }
  92. if ((argv[1][0] == 'c') || (argv[1][0] == 'C'))
  93. rle_compress("input.txt", "output.txt");
  94. else if ((argv[1][0] == 'd') || (argv[1][0] == 'D'))
  95. rle_decompress("input.txt", "output.txt");
  96. return 0;
  97. }
Add Comment
Please, Sign In to add comment