当前位置:编程学习 > 网站相关 >>

mmap函数的用法

[plain]
mmap函数的用法 (2005-11-06 09:14)  
分类: C/C++  
 
 
 
改自Wrox《Linux程序设计》 
 
 
  #include  <unistd.h> 
#include    <stdio.h> 
#include    <sys/mman.h> 
#include    <fcntl.h> 
#include    <stdlib.h> 
 
typedef struct  

    int integer; 
    char string[24]; 
}RECORD; 
 
#define NRECORDS (100) 
 
int main() 

    RECORD record, *mapped; 
    int i, f; 
    FILE *fp; 
 
    fp = fopen("records.dat", "w+"); 
    for (i = 0; i < NRECORDS; i++) 
    { 
        memset(&record, 0, sizeof(record));/* 若不清空,内容未知 */ 
        record.integer = i; 
        sprintf(record.string, "RECORD-%d", i); 
        fwrite(&record,sizeof(record), 1, fp); 
    } 
    fclose(fp); 
 
    /* 修改43条记录 */ 
    fp = fopen("records.dat", "r+"); 
    fseek(fp, 43*sizeof(record), SEEK_SET); 
    fread(&record, sizeof(record), 1, fp); 
 
    record.integer = 143; 
    sprintf(record.string, "RECORD-%d", record.integer); 
    fseek(fp, 43*sizeof(record), SEEK_SET); 
    fwrite(&record, sizeof(record), 1, fp); 
    fclose(fp); 
 
    /* 修改43条记录 */ 
    f = open("records.dat", O_RDWR); 
    mapped = (RECORD *)mmap(0, NRECORDS*sizeof(record),  
        PROT_READ|PROT_WRITE, MAP_SHARED, f, 0); 
 
    mapped[43].integer = 243; 
    sprintf(mapped[43].string, "RECORD-%d", mapped[43].integer); 
    msync((void *)mapped,NRECORDS*sizeof(record), MS_ASYNC); 
    munmap((void *)mapped,NRECORDS*sizeof(record)); 
    close(f); 
 
    return 0; 

  
补充:Web开发 , 其他 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,