Arkerone
Arkerone

Reputation: 2026

Read a file line by line with 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?

Thank you for your answers!

Upvotes: 4

Views: 2733

Answers (1)

Dietmar Kühl
Dietmar Kühl

Reputation: 153840

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

Upvotes: 7

Related Questions