Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1418898
  • 博文数量: 430
  • 博客积分: 9995
  • 博客等级: 中将
  • 技术积分: 4388
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-24 18:04
文章存档

2013年(1)

2008年(2)

2007年(14)

2006年(413)

分类:

2006-06-13 17:36:43

#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;
}
阅读(1786) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~