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

前端 未结 7 563
温柔的废话
温柔的废话 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:16

    I was also struggling on the problem because I ran uberwulu's code and also got blank line. Here is what I found. I am using the following .csv file as an example:

    date       test1  test2
    20140908       1      2
    20140908      11     22
    20140908     111    235
    

    To understand the commands in the code, please notice the following locations and their corresponding chars. (Loc, char) : ... (63,'3') , (64,'5') , (65,-) , (66,'\n'), (EOF,-).

    #include
    #include
    #include
    
    using namespace std;
    
    int main()
    {
        std::string line;
        std::ifstream infile; 
        std::string filename = "C:/projects/MyC++Practice/Test/testInput.csv";
        infile.open(filename);
    
        if(infile.is_open())
        {
            char ch;
            infile.seekg(-1, std::ios::end);        // move to location 65 
            infile.get(ch);                         // get next char at loc 66
            if (ch == '\n')
            {
                infile.seekg(-2, std::ios::cur);    // move to loc 64 for get() to read loc 65 
                infile.seekg(-1, std::ios::cur);    // move to loc 63 to avoid reading loc 65
                infile.get(ch);                     // get the char at loc 64 ('5')
                while(ch != '\n')                   // read each char backward till the next '\n'
                {
                    infile.seekg(-2, std::ios::cur);    
                    infile.get(ch);
                }
                string lastLine;
                std::getline(infile,lastLine);
                cout << "The last line : " << lastLine << '\n';     
            }
            else
                throw std::exception("check .csv file format");
        }
        std::cin.get();
        return 0;
    }  
    

提交回复
热议问题