main.c 1.3 KB

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