linux-c 利用mmap和数组方式的存取操作对结构化数据文件进行修改

这个小程序在最后映射部分(我注释的部分,在编译的时候报错,尚未解决,先记录一下)

#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(){
	/*
	MMAP
	*/
	RECORD record, *mapped;
	int i, f;
	FILE *fp;

	fp = fopen("records.dat","w+");
	for(i=0,i<NRECORDS;i++){
		record.integer = 1;
		sprintf(record.string,"RECORD-%d",i);
		fwrite(&record,sizeof(record),1,fp);
	}
	fclose(fp);

	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);

	// f = open("records.dat",O_RDWR);
	// mapped = (RECORD *)mmap(0,NRECORDS*sizeof(record),PORT_READ|PORT_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);

}

转载于:https://my.oschina.net/zhangdapeng89/blog/69760

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值