/ * Use Mmap to operate the file * /#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <sys/mman.h>/*mmap*/#include <string.h>/*memset warning*/#include <stdio.h>#define FILELENGTHintMainvoid){intFD =-1;/ * The string that will be written to the file * / Charbuf[]="Quick brown fox jumps over the lazy dog";Char*ptr = NULL;/* Open the file mmap.txt and reduce the file length to 0, create it if the file does not exist, and read/write the permission to execute */FD = open ("Mmap.txt", O_RDWR/* Readable/writable */| O_creat/ * Does not exist, created * /| O_trunc/ * Zoom out to 0*/, S_irwxu);if( -1= = FD) {/ * Failed to open file, exit * / return-1; }/ * The following code expands the length of the file to 80*/ / * Offset file offset backward to 79*/Lseek (FD, filelength-1, Seek_set);/ * Write one character at random, the length of the file is 80*/Write (FD,' A ',1);/* Map data segments in file Mmap.txt from the beginning to the Filelength byte data into memory, the operation of the file immediately displayed on the file, read/write */PTR = (Char*) mmap (NULL, Filelength, prot_read| Prot_write,map_shared, FD,0);if( (Char*)-1= = ptr) {/ * If the mapping fails, exit * / printf("Mmap failure\n"); Close (FD);return-1; }/ * Copy the string from BUF to the map area with the start address offset 16*/ memcpy(ptr+ -, BUF,strlen(BUF));/ * Cancel the file mapping relationship * /Munmap (PTR, filelength);/ * Close file * /Close (FD);return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Linux Network Programming--File space mapping mmap function