【问题标题】:memory mapped read from a fie I/O C/C++从文件读取的内存映射 I/O C/C++
【发布时间】:2018-12-06 03:41:58
【问题描述】:

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

【问题讨论】:

  • C 字符串以 0 字节结尾,大多数文件不会出现这种情况。但是,如果您像使用任何其他最后不使用哨兵值的数组一样跟踪内存的长度,当然可以。

标签: c io memory-mapped-files


【解决方案1】:

内存映射 I/O 的总体思路是,您告诉操作系统 (OS)您想要什么文件,然后它(在完成一些设置工作后)会告诉您 该文件现在在内存中的位置。

一旦执行该合约,您应该能够以任何您希望的方式(例如使用memcpy)将内容复制到该内存中或从该内存中复制,它会神奇地为您处理 I/O。

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

例如,Windows 使用显示为here 的文件映射范例,而Linux 使用mmap 允许您将已打开的文件应用于内存映射(通过其文件描述符)。

例如,这个 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.
]

【讨论】:

  • off_t sz = lseek(fd, 0, SEEK_END);?如果您已经在使用 POSIX open()mmap(),只需在打开的文件描述符上使用 fstat() 即可获取文件大小。
猜你喜欢
  • 2011-01-19
  • 1970-01-01
  • 2020-11-06
  • 2016-05-27
  • 2010-09-17
  • 1970-01-01
  • 1970-01-01
  • 2015-09-07
  • 2017-06-08
相关资源
最近更新 更多