使用动态内存压缩文件的行

时间:2015-03-27 15:23:01

标签: c

我需要创建一个返回具有以下格式的压缩行的函数,

输入:

  

pprrrinnnttttfff

输出:

  

p2r3i1n3t4f3

如果新字符串大于原始字符串,则返回原始字符串,有人可以告诉我的代码有什么问题吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *comprimir(char *s);

int main(){
    FILE* input;
   char *lineptr = NULL;
    size_t len=0, c;
    input =fopen ("input.dat", "r");
    while ((c = getline(&lineptr, &len, input))!= -1){
            lineptr = comprimir(lineptr);
            printf("%s", lineptr );
        }
    fclose(input);
}

char* comprimir (char *s){
    int len1 = strlen(s), len2=0;
    char *str, *in, *mystr;
    mystr =(char*) calloc(len1*2, sizeof(char));
    strcpy(mystr, s);
    for (str =mystr, in=mystr; *str; str++){
        len2 += 2;    
        if (len2 >= len1) {
            free(mystr);
                return s;
        }
        int count =1;
        in[0] = str[0]; printf("%s",in[0] ); in++; 
        if (len2 > len1) return s;
        while (str[0] == str[1]){
            count++;
            str++;
        }
        in[0] = '0' + count;
        in++; printf("%s", in[0] );
        if (len2 > len1) return s;
    }
    strcpy(s, in);
    free(mystr);
    return s;
}

1 个答案:

答案 0 :(得分:1)

要修复的示例

char* comprimir (char *s){
    int len1 = strlen(s), len2=0;
    char *out, *in, *mystr;
    mystr =malloc(len1 + 2);//2*len1 not required, +2 : "r" -> "r1"(len + NUM_len + NUL
    //`s` not copy to mystr, avoid overwriting
    for (out = mystr, in=s; *in;){
        int count = 1;
        *out++ = *in++;//Pre-increment `in` to reduce code.
        while (in[-1] == in[0]){
            count++;
            in++;
        }
        int num_len = sprintf(out, "%d", count);//OK even count is more than 10
        len2 += 1 + num_len;
        if (len2 >= len1) {
            free(mystr);
            return s;
        }
        out += num_len;
    }
    *out = 0;//terminate by '\0'
    strcpy(s, mystr);
    free(mystr);
    return s;
}