Can I use std::string_view with getline when parsing a file?

Viewed 1249

I recently learned about std::string_view and how it is much faster than allocating strings so I am trying to use this in place of std::string where possible.

Is there a way of optimizing a loop that parses a file line by line to use std::string_view instead?

This is the code I am working on.

    std::string line;

    // loop until we find the cabbage tag
    while (std::getline(csd, line))
    {
        //DO STUFF
        if (line.find("</STOP>") != std::string::npos)
            break;
    }
2 Answers

What you're looking for is mmap, that allows you to read into a file's data without copying them. Reading from a stream in C++ will always copy the data. You can then, of course, use std::string_view to point at the data revealed by mmap, and do all operations you like.

No. A string_view is:

  • A constant view into some storage, so you can't read into the string_view
  • Does not own the storage, but instead "refers" to some other storage, so there's nowhere for getline to put the information that it reads.

However, once you read the data into a string, you can make a string_view and pass that to a routine for parsing (avoiding passing a copy in that case).

Related