test_filemap.c 1.2 KB

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