Read a file line by line with mmap

◇◆丶佛笑我妖孽 提交于 2019-12-11 03:52:25

问题


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!


回答1:


Once you have mmap()ed the file, you can make the file available to a suitable stream buffer reading data from existing memory and then use 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); ) {
        ...
    }
}


来源:https://stackoverflow.com/questions/13535672/read-a-file-line-by-line-with-mmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!