第1个回答 2022-12-21
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 1000 // 最大长度
int main(int argc, char *argv[])
{
// 打开文件 file1.txt
FILE *infile = fopen("file1.txt", "r");
if (infile == NULL)
{
printf("Error opening file1.txt!\n");
return 1;
}
// 打开文件 file2.txt
FILE *outfile = fopen("file2.txt", "w");
if (outfile == NULL)
{
printf("Error opening file2.txt!\n");
return 1;
}
char s[MAX_LEN]; // 用于存储读取的字符串
fgets(s, MAX_LEN, infile); // 读取字符串
// 利用 RLC 算法进行压缩
char c = s[0]; // 当前字符
int count = 1; // 当前字符的出现次数
for (int i = 1; s[i] != '\0'; i++)
{
if (s[i] == c)
{
count++;
}
else
{
// 输出当前字符及其出现的次数
fprintf(outfile, "%c%d", c, count);
c = s[i];
count = 1;
}
}
// 输出最后一个字符及其出现的次数
fprintf(outfile, "%c%d", c, count);
// 关闭文件
fclose(infile);
fclose(outfile);
return 0;
}