1 #include <sys/mman.h> 2 #include <sys/types.h> 3 #include <sys/stat.h> 4 #include <fcntl.h> 5 #include <unistd.h> 6 #include <stdio.h> 7 #include <stdlib.h> 8 9 int main() 10 { 11 // 打开文件 12 int fd = open("example.txt", O_RDWR | O_CREAT | O_TRUNC, 0777); 13 14 if (fd == -1) 15 { 16 perror("open"); 17 exit(EXIT_FAILURE); 18 } 19 20 write(fd, "HelloWorld!", 11); 21 char buf[12]; 22 buf[11] = '\0'; 23 close(fd); 24 25 fd = open("example.txt", O_RDWR); 26 read(fd, buf, 11); 27 printf("File content: %s\n", buf); 28 29 // 将文件映射到内存 30 void *map = mmap(NULL, 11, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); 31 if (map == MAP_FAILED) 32 { 33 perror("mmap"); 34 close(fd); 35 exit(EXIT_FAILURE); 36 } 37 printf("mmap address: %p\n", map); 38 39 // 关闭文件描述符 40 // close(fd); 41 42 // 访问和修改文件内容 43 char *fileContent = (char *)map; 44 printf("change 'H' to 'G'\n"); 45 fileContent[0] = 'G'; // 修改第一个字符为 'G' 46 printf("mmap content: %s\n", fileContent); 47 48 // 解除映射 49 printf("unmap\n"); 50 if (munmap(map, 11) == -1) 51 { 52 perror("munmap"); 53 exit(EXIT_FAILURE); 54 } 55 56 fd = open("example.txt", O_RDWR); 57 read(fd, buf, 11); 58 printf("File content: %s\n", buf); 59 60 return 0; 61 } 62