Read end file to start

Asked

Viewed 281 times

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 to read from end of file to start

1 answer

0


For the record, I see this as something merely funny and with no real application, yet it manages to do so using fseek and ftell.

Start by positioning yourself at the end with fseek and with ftell discovers the position of this end. Then decreases the position manually and uses again fseek 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 instruction in focus is:

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

SEEK_SET means positioning at the beginning. In this case it will be positioned posicao bytes from the beginning. How posicao decreases with 1 in 1 in the while, is positioning itself more and more towards the beginning.

A more performative solution involves reading the entire file (from start to finish) to a char[] and then use this array backwards, which avoids having to do multiple fseeks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.