gpt4 book ai didi

c - C 中的 RLE 文本压缩

转载 作者:行者123 更新时间:2023-12-02 21:21:07 25 4
gpt4 key购买 nike

我想编写一个代码,将以下文本转换为:“aaaaaaabbbb”到:“a7b4”。它应该从一个文件读取并写入另一个文件。这是代码的错误部分,我无法使其工作。寻求帮助..

        fread(&fx,sizeof(fx),1, fin);      // read first character
while(!feof(fin))
{
fread(&z, sizeof(z),1, fin); //read next characters

if(z!=fx) { fputs(fx, fout);
fputs(poc, fout);
poc=1; // if its different count=1
fx=z; // and z is new character to compare to
}
else poc++;


}

fputs(fx, fout);
fputs(poc, fout);

最佳答案

这是我用注释解决问题的代码(不是最佳解决方案)...希望它对您自己的代码和程序有所帮​​助!!

#include <stdio.h> 
#include <string.h>

int main(int argc, char *argv[])
{
/* file is a pointer to the file input where to read the line */
/* fileto is a pointer to the file output where we will put */
/* the compressed string */
FILE* file, *fileto;
file=fopen("path_to_input_file","r");
fileto=fopen("path_to_output_file","w");
/* check if the file is successfully opened */
if (file!=NULL)
{
/* the str will contain the non compressed str ing */
char str[100];
/* read the non compressed string from the file and put it */
/* inside the variable str via the function fscanf */
fscanf(file,"%[^\n]s",str);
/* the variable i will serve for moving character by character */
/* the variable nb is for counting the repeated char */
int i=0,nb=1;
for (i=1;i<strlen(str);i++)
{
/* initialization */
nb=1;
fprintf(fileto,"%c",str[i-1]);
/* loop to check the repeated charac ters */
while (i<strlen(str) && str[i]==str[i-1])
{
i++;
nb++;
}
fprintf(fileto,"%d",nb);

}
/* handle the exception for the last character */
if(strlen(str)>=2 && str[strlen(str)-1]!=str[strlen(str)-2])
fprintf(fileto,"%c%d",str[strlen(str)-1],1);
/* handle the string when it is composed only by one char */
if(strlen(str)==1)
fprintf(fileto,"%s%d\n",str,nb);



fclose(fileto);
fclose(file);
}

return 0;
}

关于c - C 中的 RLE 文本压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27642948/

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