Thread: :| file i/o read last line of .txt

  1. #1
    Unregistered
    Guest

    :| file i/o read last line of .txt

    as the file says how can i read the last line of a text file and store its input into a variable i ahve been looking into tellgp but dont know where to go from there :|

    datafile.seekp(0, ios::end);

  2. #2
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    If the data in the file are not of standard "size", that is all of a given primitive type or user defined class, then you will need to read the file into the program, find the last line, and do whatever you want with it while ingoring the rest of the file contents.

    If, on the other hand, the data in the file is of predictable sized "packets", where the size is the number of bits of memory each packet has to have, and you knew how many packets there are in the file, then you could try something like this:

    struct packet
    {
    char line[80];
    };


    //somehow place file pointer at beginning of last packet of file
    fseek((sizeOfPacket * (NumberOfPackets - 1));

    //read in last line
    ifstream fin("filename.txt");
    packet dummy;
    fin.getline(dummy.line, 80);

    mind you I have never done this, but I think everything is avaiable in C++ to do it. I suspect that this is how field data in a databases are retrieved from memory. Exactly how you make sure every line uses the full 80 bytes of memory allocated to it and the exact syntax of fseek() and/or related functions will need to be worked out and/or looked up. If data in packet were an int or a double or a char, etc. then the need to assure same "size" in every packet becomes less problematic. Somebody can probably help us out.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Is there any way to read a line from a text file?
    By megareix in forum C Programming
    Replies: 13
    Last Post: 01-09-2009, 01:13 PM
  2. Subtle(?) File I/O Problem
    By cecomp64 in forum C Programming
    Replies: 9
    Last Post: 07-16-2008, 11:39 AM
  3. go to next line in .txt file
    By adr in forum C++ Programming
    Replies: 6
    Last Post: 03-21-2006, 10:23 PM
  4. unable to read double A[0] and A[1] when n=1
    By sweetarg in forum C Programming
    Replies: 2
    Last Post: 10-25-2005, 12:35 PM
  5. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM