2014-12-24 33 views
2

我想写一个代码,将例如这个文本转换为:“aaaaaaabbbb”转换为:“a7b4”。 它应该从一个文件读取并写入另一个文件。这里是代码的错误部分,我不能让它工作。泰为帮助..在C中的RLE文本压缩

 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); 

回答

2

这是我的代码(不是最佳解决方案)解决与评论问题....希望它有助于您自己的代码和程序!

#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; 
} 
2
fputs(poc, fout); 
     ^^^ 

poc是一个整数类型。 fputs()的第一个参数是一个字符串类型。你不能混合和匹配这两个。

考虑,而不是使用:

fprintf(fout, "%d", poc); 

但要记住的是,输出有时是模糊的,当计数大于10。例如,输出:

12345 

可以代表(例如)1 x 2, 3 x 451 x 23, 4 x 5