|
#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++) {
record.integer = i;
sprintf(record.string,”RECORD-%d”,i);
fwrite(&record,sizeof(record),1,fp);
}
fclose(fp);
2 我们现在改变记录43到143的整数值,并且写第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);
3 为了将整数值改变为243(并且更新记录字符串),我们将这些记录映射到内存,并且访问第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);
exit(0);
}
关于程序第三部分中
mapped = (RECORD *)mmap(0, NRECORDS*sizeof(record),
PROT_READ|PROT_WRITE, MAP_SHARED, f, 0);
看得不是很明白,想求解一下(RECORD *)是强制类型转换吗?这个mmap处理以后应该是把文件“records.dat”所有的记录都取出来了,如果用(RECORD *)来强制类型转换,好像很难理解转换以后mmapped里面的结构是怎么的?不知道那位高手能够指点一下? |
|