Read a file line by line with mmap

Ark*_*one 2 c++ mmap file

I have a program that reads a file line by line whose size varies, i would like use mmap but how use it to read a file line by line?

Thank you for your answers!

Die*_*ühl 5

一旦你mmap()编的文件,可以使文件可从现有的内存合适的流缓冲区中读取数据,然后使用std::getline():

#include <streambuf>
#include <string>
#include <istream>

struct membuf
    std::streambuf {
    membuf(char* start, size_t size) {
        this->setg(start, start, start + size);
    }
};

int main() {
    // mmap() the file yielding start and size
    membuf      sbuf(start, size);
    std:istream in(&sbuf);
    for (std::string line; std::getline(in, line); ) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)