从FIE I / O C / C ++读取的内存映射

时间:2018-12-06 03:41:58

标签: c io memory-mapped-files

我在映射的内存领域是新手,我想知道是否有什么方法可以使用映射到字符串的内存读取文本文件。我真的不知道如何开始编写代码。

1 个答案:

答案 0 :(得分:2)

具有内存映射I / O的一般想法是,您告诉操作系统(OS)您想要的文件,并且它(在进行了一些设置工作之后)告诉您< em>该文件现在在内存中的位置。

一旦执行了合同,您应该能够以您希望的任何方式(例如,使用memcpy)来复制内存中的内容,并且它将神奇地为您处理I / O。< / p>

详细信息取决于您使用的操作系统,因为ISO C标准没有指定此行为-因此,它是特定于操作系统的。

例如,Windows使用here所示的文件映射范例,而Linux使用mmap允许您对已经打开的文件进行内存映射(通过其文件描述符)。 / p>

通过示例的方式,此Linux程序由于其错误检查和进度报告而非常繁琐,它会映射file.txt文件并输出其内容:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>

// Helper function to minimise error code in main.

static int clean(
    int retVal,     // value to return.
    char *err,      // error/NULL, allows optional %s for strerror(errno).
    int fd,         // fd/-1 to close.
    void *filMem,   // memory/NULL to unmap.
    off_t sz,       // size if unmapping.
    void *locMem    // memory/NULL to free.
) {
    if (err)     printf (err, strerror(errno));
    if (locMem)  free(locMem);
    if (filMem)  munmap(filMem, sz);
    if (fd >= 0) close(fd);
    return retVal;
}

int main(void) {
    int fd = open("file.txt", O_RDONLY);
    if (fd < 0) return clean(-1, "Can't open: %s\n", -1, NULL, 0, NULL);
    printf("File opened okay, fd = %d.\n", fd);

    off_t sz = lseek(fd, 0, SEEK_END);
    if (sz == (off_t) -1) return clean(-1, "Can't seek: %s\n", fd, NULL, 0, NULL);
    printf("File size is %ld.\n", sz);

    void *fileArea = mmap(NULL, sz, PROT_READ, MAP_SHARED, fd, 0);
    if (! fileArea) return clean(-1, "Can't map: %s\n", fd, NULL, 0, NULL);
    printf("File mapped to address %p.\n", fileArea);

    char *localArea = calloc(1, sz + 1);
    if (! localArea) return clean(-1, "Can't allocate\n", fd, fileArea, sz, NULL);
    memcpy(localArea, fileArea, sz);
    printf("Data copied to %p, result is [\n%s]\n", localArea, localArea);

    return clean(0, NULL, fd, fileArea, sz, localArea);
}

在我的本地系统上运行该结果,可以从以下记录中看到结果:

pax$ cat file.txt
...This is the input file content.

pax$ ./testprog
File opened okay, fd = 3.
File size is 35.
File mapped to address 0x7f868a93b000.
Data copied to 0x1756420, result is [
...This is the input file content.
]
相关问题