c++ fastest way to read only last line of text file?

前端 未结 7 562
温柔的废话
温柔的废话 2020-11-27 20:35

I would like to read only the last line of a text file (I\'m on UNIX, can use Boost). All the methods I know require scanning through the entire file to get the last line wh

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 21:14

    Initially this was designed to read the last syslog entry. Given that the last character before the EOF is '\n' we seek back to find the next occurrence of '\n' and then we store the line into a string.

    #include 
    #include 
    
    int main()
    {
      const std::string filename = "test.txt";
      std::ifstream fs;
      fs.open(filename.c_str(), std::fstream::in);
      if(fs.is_open())
      {
        //Got to the last character before EOF
        fs.seekg(-1, std::ios_base::end);
        if(fs.peek() == '\n')
        {
          //Start searching for \n occurrences
          fs.seekg(-1, std::ios_base::cur);
          int i = fs.tellg();
          for(i;i > 0; i--)
          {
            if(fs.peek() == '\n')
            {
              //Found
              fs.get();
              break;
            }
            //Move one character back
            fs.seekg(i, std::ios_base::beg);
          }
        }
        std::string lastline;
        getline(fs, lastline);
        std::cout << lastline << std::endl;
      }
      else
      {
        std::cout << "Could not find end line character" << std::endl;
      }
      return 0;
    }
    

提交回复
热议问题