user1767077
user1767077

Reputation: 117

What is the most effective way to read the last line of a file in c++?

im trying to store a large list of prime numbers in a text file and if I end my program i need to be able to read the line of the file to see where I left off. I dont know how to read the last line with out reading every line of the file first.

Upvotes: 3

Views: 377

Answers (5)

Pete Becker
Pete Becker

Reputation: 76235

I don't know either. Just write the last value into a separate file, and read that value to know where to resume.

Upvotes: 3

Ed Heal
Ed Heal

Reputation: 59987

If you know the maximum length of line this will be easy.

Just go the the pointer that is the location of the end of file less this value.

Start reading lines from there and put them in a buffer. Clear buffer when the previous character was a new line

When you ran out of file the buffer will contain it.

If you do not know the maximum length you can always read the file backwards.

Upvotes: 0

David Saxon
David Saxon

Reputation: 1436

Seek to the very end of the file, and just read backwards till you find the newline character which means you have found the the start of the last line

Upvotes: 1

Candost
Candost

Reputation: 1029

You can calculate the bytes of your numbers.

For example you have 5 number and you want to read last number.

1 integer is 4 byte. So you can move 4*4=16 Byte in file using fseek. After that you can read last line.

fseek (file , 16 , SEEK_SET);

SEEK_SET means begining of file.

Upvotes: 1

dutt
dutt

Reputation: 8209

You could use setg() to jump to the end of the file and do guesses how far a line is. If there's a newline between your point and the end of the file then you're in the next-to-last line and know what the last line is.

But Pete Beckers solution is a lot nicer, I'd go with that instead.

Upvotes: 2

Related Questions