Read file from end to start [closed]

0
....
         fseek(arq, 0, SEEK_END);
                while(!feof(arq)){
                    //fgets(&ch,2,arq);
                    fread(&ch, sizeof(char), 1, arq);
                    //printf("\n%c",ch);
                    num = atoi(&ch);
                    vem=makenode();
                    vem->numero=num;
                    lista=insertfirst(lista,vem);
                }

....

How do I read from the end of the file to the start

    
asked by anonymous 04.04.2018 / 21:18

1 answer

0

For the record, I see this as something purely funny and with no real application, yet you can do it by using fseek and ftell .

It begins by positioning itself at the end with fseek and with ftell finds the position of that end. Then it decreases the position manually and uses fseek again to read from that byte:

int main(){
    FILE *arq = fopen("teste.txt","r");
    fseek(arq, 0, SEEK_END); //ir para o fim do arquivo
    long posicao = ftell(arq); //assumir a posição como fim
    char ch;

    while(posicao >= 0){
        fseek(arq, posicao, SEEK_SET); //reposicionar de acordo com a posicao
        fread(&ch, sizeof(char), 1, arq); //ler o caratere
        printf("%c\n",ch);
        posicao--; //andar uma posição para trás
    }

    return 0;
}

The focus statement is:

fseek(arq, posicao, SEEK_SET); // arquivo, offset, tipo de posicionamento

SEEK_SET means positioning at startup. In this case, posicao bytes will be positioned from the beginning. As posicao decreases from 1 to 1 to while , it is increasingly positioning itself to the beginning.

A more performative solution is to read the whole file (start to finish) to a char[] and then use that array backwards, which avoids having to do multiple fseek s. p>     

04.04.2018 / 23:16