这本是《深圳理解计算机系统》第九章的练习题
题目假设有一个文件hello.txt,内容是“Hello,world!\n“,用 c 编写一个程序,使用mmap 修改文件内容 为 “Jello,word!\n”
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
void main()
{
int fd,len;
char *buf;
len = 64;
fd=open("/data/hello.txt",O_RDWR,0);
if(fd <0 )
{
printf("open error\n");
}
ftruncate(fd,len); // 改变文件大小
buf = mmap(NULL,len,PROT_WRITE,MAP_SHARED ,fd,0);
if(buf == -1)
{
printf("mmap return error\n");
}
memset(buf,64,0);
sprintf(buf,"hello_modify!\n");
munmap(buf,64);
close(fd);
}
需要注意的有,
没有 ftruncate(fd,len)的话,超过原始文件大小将写入不了,所以需要先修改文件大小。