read file backwards (last line first)

Viewed 40842

file looks like this:

abcd
efgh
ijkl

I want to read the file using C so that it read the last line first:

ijkl
efgh
abcd

I cannot seem to find a solution that does not use an array for storage. Please help.

edit0: Thanks for all the answers. Just to let you know, I am the one creating this file. So, can I create in a way its in the reverse order? Is that possible?

6 Answers

I know this question has been awnsered, but the accepted awnser does not contain a code snippet and the other snippets feel too complex. This is my implementation:

#include <stdio.h>

long file_size(FILE* f) {
    fseek(f, 0, SEEK_END); // seek to end of file
    long size = ftell(f); // get current file pointer
    fseek(f, 0, SEEK_SET); // seek back to beginning of file
    return size;
}

int main(int argc, char* argv[]) {
    FILE *in_file = fopen(argv[1], "r");
    long in_file_size = file_size(in_file);
    printf("Got file size: %ld\n", in_file_size);

    // Start from end of file
    fseek(in_file, -1, SEEK_END); // seek to end of file
    for (int i = in_file_size; i > 0; i--) {
        char current_char = fgetc(in_file); // This progresses the seek location
        printf("Got char: |%c| with hex: |%x|\n", current_char, current_char);
        fseek(in_file, -2, SEEK_CUR); // Go back 2 bytes (1 to compensate)
    }
    printf("Done\n");

    fclose(in_file);
}
Related