Fastest way to find the number of lines in a text (C++)

后端 未结 8 968
臣服心动
臣服心动 2020-12-07 23:12

I need to read the number of lines in a file before doing some operations on that file. When I try to read the file and increment the line_count variable at each iteration u

8条回答
  •  孤街浪徒
    2020-12-07 23:57

    Remember that all fstreams are buffered. So they in-effect do actually reads in chunks so you do not have to recreate this functionality. So all you need to do is scan the buffer. Don't use getline() though as this will force you to size a string. So I would just use the STL std::count and stream iterators.

    #include 
    #include 
    #include 
    #include 
    
    
    struct TestEOL
    {
        bool operator()(char c)
        {
            last    = c;
            return last == '\n';
        }
        char    last;
    };
    
    int main()
    {
        std::fstream  file("Plop.txt");
    
        TestEOL       test;
        std::size_t   count   = std::count_if(std::istreambuf_iterator(file),
                                              std::istreambuf_iterator(),
                                              test);
    
        if (test.last != '\n')  // If the last character checked is not '\n'
        {                       // then the last line in the file has not been 
            ++count;            // counted. So increement the count so we count
        }                       // the last line even if it is not '\n' terminated.
    }
    

提交回复
热议问题