开发者

Reading a file from the end [duplicate]

This question already has answers here: 开发者_StackOverflow社区 Read a file backwards? (7 answers) Closed 8 years ago.

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

  1. Seek to last character
  2. Start searching for NEWLINE character from current character
  3. If not newline, add character to string
  4. If newline, reverse the string to get the line
  5. Seek to previous character
  6. 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:

  1. find the file size
  2. seek to the offset desired
  3. read
  4. seek to the next offset
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜