mmap和munmap对文件进行操作(读写等)
生活随笔
收集整理的這篇文章主要介紹了
mmap和munmap对文件进行操作(读写等)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
//mmap、munmap函數的使用
#include <stdio.h> #include <string.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <sys/mman.h>void sys_err(char *str) {perror(str);exit(1); }int main(void) {char *mem;int len = 0;int fd = open("hello244", O_RDWR|O_CREAT|O_TRUNC, 0644); //新創建的文件或者已經存在的文件,都截斷為0if (fd < 0)sys_err("open error");ftruncate(fd, 20); //文件大小為20 /*len = lseek(fd, 3, SEEK_SET); write(fd, "e", 1); //實質性完成文件拓展,大小為4*/printf("The length of file = %d\n", len);mem = mmap(NULL, 20, PROT_WRITE, MAP_SHARED, fd, 0); //自己完成隱式轉換if (mem == MAP_FAILED) //出錯判斷sys_err("mmap err");close(fd); //可以關閉文件,以后通過映射區來操作文件strcpy(mem, "xxx");printf("%s\n", mem);if (munmap(mem,20) < 0) //完全對應sys_err("munmap");return 0; }?
總結
以上是生活随笔為你收集整理的mmap和munmap对文件进行操作(读写等)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 原神托马圣遗物怎么搭配
- 下一篇: 成都欢乐谷青少年票要带学生证吗