How to read the last line of a file in Managed C++

Hi,
well this is a very stupid question but I can't find the efficient way. I need to read the last line of a very very large file. So, I don't want to open it and loop through all the lines but I need another way. Help, please, anyone can post a code snippet


Answer this question

How to read the last line of a file in Managed C++

  • Stan Spotts

    Ok, for now I resolved with this:

    DateTime getLastDateTimeFromFile(String* fileName){
        StreamReader* sr = File::OpenText(fileName);

        String *lastLine, *input;
        while((input=sr->ReadLine())!=NULL){
            lastLine = input;
        }
        return lastLine->Substring(0, 10)->ToDateTime(NULL);
    }

    But as I said is very inefficient cause the file has A LOT of lines. Still searching and please help!


  • mukri743

    I believe you can use the FileStream class (System.IO.FileStream) where it supports randon access to files.

    Here is a link for the class itself:
    http://msdn2.microsoft.com/library/y0bs3w9t(en-us,vs.80).aspx

    Also, the class provides a Seek method that can be used for your purpose. Take a look at the below link, it includes some samples:
    http://msdn2.microsoft.com/library/hfkdy2ws(en-us,vs.80).aspx

    Hope this helps!

    Thanks,
      Ayman.

  • boharp

    Try to use: FileStream::Seek( Offset, SeekOrigin::End )

    FileStream^ fs = gcnew FileStream( "path", FileMode::Open );
    fs->Seek( -4,  SeekOrigin::End );

    This the file pointer to the last 4 bytes from the end back of the file.

    Bye
    Martin

  • How to read the last line of a file in Managed C++