Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: read only last line of a file. No loops

Tags:

c

file-io

Using C, is there a way to read only the last line of a file without looping it's entire content?

Thing is that file contains millions of lines, each of them holding an integer (long long int). The file itself can be quite large, I presume even up to 1000mb. I know for sure that the last line won't be longer than 55 digits, but could be 2 only digits as well. It's out of options to use any kind of database... I've considered it already.

Maybe its a silly question, but coming from PHP background I find it hard to answer. I looked everywhere but found nothing clean.

Currently I'm using:

if ((fd = fopen(filename, "r")) != NULL) // open file
{
    fseek(fd, 0, SEEK_SET); // make sure start from 0
    while(!feof(fd))
    {
        memset(buff, 0x00, buff_len); // clean buffer
        fscanf(fd, "%[^\n]\n", buff); // read file *prefer using fscanf
    }
    printf("Last Line :: %d\n", atoi(buff)); // for testing I'm using small integers
}

This way I'm looping file's content and as soon as file gets bigger than ~500k lines things slow down pretty bad....

Thank you in advance. maxim

like image 363
MAXIM Avatar asked Dec 09 '12 19:12

MAXIM


Video Answer


1 Answers

Just fseek to fileSize - 55 and read forward?

like image 117
Reunanen Avatar answered Sep 27 '22 22:09

Reunanen