mmap将文件映射到内存中,然后用指针指向内存,就可以方便高效的操作了。
创建文件map_file,长度为256,映射到内存中,然后写入字符串,结束后用cat查看是否写入了。
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <errno.h>
#include <syslog.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/mman.h>
#define FILE_ "map_file"
#define FILE_MODE S_IRUSR | S_IWUSR
int main(int argc, char* argv[])
{
int fd;
char *ptr;
char str[256];
int i=7;
int *pi;
fd = open(FILE_, O_RDWR | O_CREAT, FILE_MODE);
if(fd == -1)
{
printf("file open failed!\n");
exit(2);
}
str[0]='A';
lseek(fd,255,SEEK_SET);
write(fd,str,sizeof(char));
ptr = mmap(NULL, sizeof(char)*256, PR