Reading a file from the end [duplicate]
I would like to read a file line by line from the end. I looked at a c++ function like fgets but file is being read in reverse.
Unless the file is really big, just read the entire file into a std::vector<std::string>
, and then use the reverse_iterator
you get from std::vector<>::rbegin()
Unfortunately, I am not aware of any built-in function that would read in reverse. One option would be to implement algorithm of one's own as shown below using fseek, fread and ftell
- Seek to last character
- Start searching for NEWLINE character from current character
- If not newline, add character to string
- If newline, reverse the string to get the line
- Seek to previous character
- Repeat steps 2, 3, 4, 5 till you reach start of file.
You can use ftell, fseek
functions to reach last character and then to previous character.
If the file size is small use MSalters answer.
If the file size is large, you will have to do the filepointer book keeping manually using iostream::seekg
functions. The algorithm would be something like:
- find the file size
- seek to the offset desired
- read
- seek to the next offset
精彩评论