Thread: Last line or entry in a file

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    1

    Last line or entry in a file

    Code:
    Does anyone know how I can read the last entry in a file? I have a file that I receive everyday but I want to only be able to report out the last entry or display the last entry as the file is quite large but new entries get written to it on a daily basis. 
    
    In such I will like it to display only entries for each current day in the file.
    
    I have downloaded the Bloodshed Dev-C++ and have tried using this program which I found online
    
    #include <stdio.h>
    #include <string.h>
    #define MYSIZE 10
    
    FILE *fp;
    char buf[MYSIZE + 1], buf2[MYSIZE + 1];
    char *ptr;
    fp = fopen("filename", "r");
    fseek(fp, MYSIZE, SEEK_END); 
    fread(buf, sizeof(char), MYSIZE, fp);
    fclose(fp);
    ptr = strrchr(buf, '\n');
    if (ptr) {
       // We've found the data
       strcpy(buf2, ptr+1);
    }
    
    Buy honestly I dont have a clue.  I have compiled it and run it and it stops at 
    
    fp = fopen("filename", "r");
    
    I have put in the following
    fp = fopen("ggg.txt", "r");
    
    but it still does not work? 
    
    Help
    Thanks

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Try to put the code-tags around ONLY the code in your post - that way your explanation doesn't get really long.

    To find the last entry, you would have to read the file backwards. There are a couple of approaches, but the obvious one is to find the end of the file (fseek(f, 0, SEEK_END) will do that), use ftell() to find where the end is, and then use fseek(f, endpos - (numread+1), SEEK_SET), using fgetc() read the characters (into a string?), and check for a newline '\n' to be the input. [Obviously, there will be a newline at the VERY end too, so you need the previous newline to that].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Trouble writing to file using fwrite()
    By yougene in forum C Programming
    Replies: 4
    Last Post: 12-30-2008, 05:13 PM
  2. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM