gpt4 book ai didi

c - rle压缩算法c

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:46:35 30 4
gpt4 key购买 nike

我必须在 c 中使用转义字符 (Q) 执行 rle 算法

例如,如果我有这样的输入:AAAAAAABBBCCCCDDDDDDEFG
输出必须是:QA7BBBCCCQD6FFG

这是我编写的代码:

#include <stdio.h>
#include <stdlib.h>

void main()
{
FILE *source = fopen("Test.txt", "r");
FILE *destination = fopen("Dest.txt", "w");
char carCorrente; //in english: currentChar
char carSucc; // in english: nextChar
int count = 1;

while(fread(&carCorrente, sizeof(char),1, source) != 0) {
if (fread(&carCorrente, sizeof(char),1, source) == 0){
if(count<=3){
for(int i=0;i<count;i++){
fprintf(destination,"%c",carCorrente);
}
}
else {
fwrite("Q",sizeof(char),1,destination);
fprintf(destination,"%c",carCorrente);
fprintf(destination,"%d",count);
}
break;
}
else fseek(source,-1*sizeof(char), SEEK_CUR);

while (fread(&carSucc, sizeof(char), 1, source) != 0) {
if (carCorrente == carSucc) {
count++;
}
else {
if(count<=3){
for(int i=0;i<count;i++){
fprintf(destination,"%c",carCorrente);
}
}
else {
fwrite("Q",sizeof(char),1,destination);
fprintf(destination,"%c",carCorrente);
fprintf(destination,"%d",count);
}

count = 1;
goto OUT;
}
}

OUT:fseek(source,-1*sizeof(char), SEEK_CUR); //exit 2° while
}
}

问题是当我有这样的输入时:ABBBCCCDDDDDEFGD
在这种情况下,输出为:QB4CCCQD5FFDD
我不知道为什么 :(

最佳答案

不需要像您那样使用 Fseek 倒带,这里是通过使用简单的计数器和当前序列字符在不使用它的情况下编写的代码。

C 实现:

#include<stdio.h>
#include<stdlib.h>

void main()
{
FILE *source = fopen("Test.txt", "r");
FILE *destination = fopen("Dest.txt", "w");
char currentChar;
char seqChar;
int count = 0;

while(1) {
int flag = (fread(&currentChar, sizeof(char),1, source) == 0);

if(flag||seqChar!=currentChar) {

if(count>3) {
char ch = 'Q';
int k = count;
char str[100];
int digits = sprintf(str,"%d",count);
fwrite(&ch,sizeof(ch),1,destination);
fwrite(&seqChar,sizeof(ch),1,destination);
fwrite(&str,sizeof(char)*digits,1,destination);
}
else {
for(int i=0;i<count;i++)
fwrite(&seqChar,sizeof(char),1,destination);
}
seqChar = currentChar;
count =1;
}

else count++;

if(flag)
break;
}

fclose(source);
fclose(destination);
}

关于c - rle压缩算法c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20176338/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com