通过倒转丢失最后一个(第一个)角色

时间:2015-01-07 08:35:51

标签: c linux posix

如果文件以字符结尾而不是“\ n”(十六进制0A),我的反向函数不会返回最后一个(第一个)字符。我的系统是Posix。可以随时帮忙吗? 输出:

54
3. sor Csörnyeföl   //here failed "d" the last character
2. sor Szentendre
1. sor Budapest

以下是代码:

void rf_revers(FILE *fp) {
    int i, size, start, loop, counter;
    char *buffer;
    char line[256];
    start = 0;
    fseek(fp, 0, SEEK_END);
    size = ftell(fp);
    printf("%d\n", size); // for test that fseek/ftell giving me the right value
    buffer = malloc((size+1) * sizeof(char));

    for (i=0; i< size; i++) {
        fseek(fp, size-1-i, SEEK_SET);
        buffer[i] = fgetc(fp);

        if(buffer[i] == 10) {
            if(i != 0) {
                counter = 0;
                for(loop = i; loop > start; loop--) {
                    if((counter == 0) && (buffer[loop] == 10)) {
                        continue;
                    }
                    line[counter] = buffer[loop];
                    counter++;
                }
                line[counter] = 0;
                start = i;
                printf("%s\n",line);
            }
        }
    }

    if(i > start) {
        counter = 0;
        for(loop = i; loop > start; loop--) {
            if((counter == 0) && ((buffer[loop] == 10) || (buffer[loop] == 0))) {
                continue;
            }
            line[counter] = buffer[loop];
            counter++;
        }
        line[counter] = 0;
        printf("%s\n",line);

        return;
    }
}

- [抱歉英语不好] -

1 个答案:

答案 0 :(得分:1)

我想到了,试了一下,但及时找到了解决方案。

for(loop = i; loop >= start; loop--) { // change loop > start to >=
    if(/*(counter == 0) &&*/ (buffer[loop] == 10)) {

if(i > start) {
    counter = 0;
    for(loop = i-1; loop > start; loop--) {