Ita*_*den 2 c io memory-mapped-files
我是内存映射领域的新手,我想知道是否有任何方法可以使用映射到字符串的内存来读取文本文件。我真的不知道如何开始编写代码。
内存映射 I/O 的总体思路是,您告诉操作系统 (OS) 您想要什么文件,它(在完成一定量的设置工作之后)会告诉您该文件现在在内存中的位置。
一旦执行了该合约,您应该能够以您希望的任何方式(例如使用memcpy)将内容复制到该内存中或从该内存中复制内容,并且它将神奇地为您处理 I/O。
详细信息取决于您使用的操作系统,因为 ISO C 标准没有指定此行为 - 因此它是特定于操作系统的。
例如,Windows 使用此处所示的文件映射范例,而 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);
}
Run Code Online (Sandbox Code Playgroud)
在我的本地系统上运行该程序,可以从以下记录中看到结果:
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.
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2008 次 |
| 最近记录: |