Guest User

Untitled

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