使用mmap逐行读取文件 [英] Read a file line by line with mmap

查看:944
本文介绍了使用mmap逐行读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序可以逐行读取大小不一的文件,我想使用mmap,但是如何用它逐行读取文件?

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?

谢谢您的回答!

推荐答案

一旦您对文件进行了mmap()处理,就可以使该文件可用于合适的流缓冲区,以从现有内存中读取数据,然后使用std::getline():

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); ) {
        ...
    }
}

这篇关于使用mmap逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆