Linux Network Programming--File space mapping mmap function

Source: Internet
Author: User


/ * 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.