mmap函数的简单示例
时间: 2023-08-11 11:16:32 浏览: 48
下面是一个简单的 mmap() 函数的示例,用于将文件的前10个字节映射到内存中:
```c
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
int main() {
char *addr;
int fd = open("test.txt", O_RDONLY); // 打开文件,只读模式
if (fd == -1) {
perror("open");
return -1;
}
addr = mmap(NULL, 10, PROT_READ, MAP_PRIVATE, fd, 0); // 将文件的前10个字节映射到内存中
if (addr == MAP_FAILED) {
perror("mmap");
return -1;
}
close(fd); // 关闭文件
printf("The first 10 bytes of the file:\n");
for (int i = 0; i < 10; i++) {
printf("%c", *(addr + i)); // 输出映射到内存中的内容
}
munmap(addr, 10); // 解除映射
return 0;
}
```
上述示例中,我们首先打开了一个文件,然后调用 mmap() 函数将文件的前10个字节映射到内存中,并将映射得到的内存起始地址赋值给指针变量 addr。接着,我们输出了映射到内存中的内容,并最后调用 munmap() 函数解除映射。需要注意的是,在使用 mmap() 函数映射文件时,需要在打开文件时指定文件打开方式。例如,上述示例中我们指定了 O_RDONLY,代表以只读模式打开文件。