我必须做RLE算法在C与转义字符(Q)RLE压缩算法的c
例如,如果我有等的输入:AAAAAAABBBCCCDDDDDDEFG
输出必须是: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
,我不知道为什么:(
你知道'fread'和其他阅读功能的文件提前在文件中读取位置,不是吗?所以当你只检查0而不存储结果时,A就会被吃掉。另外,请考虑使用'c = getc(f)'而不是'fread',它更适合更长的数据块。 –
是的,我知道这个原因:
fseek(source,-1 * sizeof(char),SEEK_CUR); –
如果我使用getc我怎么能回到文件中的指针? –