通过反转丢失最后一个(第一个)字符

Lose the last (first) character by reversing

如果文件以字符而不是“\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;
    }
}

--[抱歉英语不好]--

想了想,也试了,总算找到了解决办法

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