日期:2014-05-16  浏览次数:20702 次

linux下c通过虚拟地址映射读写文件
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<string.h>
#include<sys/mman.h>
struct stu
{
	char name[20];
	int age;
	float score;
};
//1 打开文件,2 映射到虚拟地址,3 写入数据,4 卸载虚拟地址,5关闭文件
main()
{
	int fd;
	struct stu *s;
	struct stat st;
	int size;
	int count;
	struct stu record;
	memset(&record,0,sizeof(struct stu));
	fd=open("newstu.dat",O_RDWR|O_CREAT|O_EXCL,0666);
	if(fd==-1)
	{
		fd=open("newstu.dat",O_RDWR);
		if(fd==-1) printf("::%m\n"),exit(-1);
	}
	fstat(fd,&st);
	size=st.st_size;//原大小 
	count=size/sizeof(struct stu);
	ftruncate(fd,size+sizeof(struct stu));;//改变文件大小,在munmap前调用就行,+ 就是增大,-就是减小
	s=mmap(0,size+sizeof(struct stu),
			PROT_READ|PROT_WRITE,
			MAP_SHARED,fd,0);
	//*
	printf("输入姓名:");
	scanf("%s",s[count].name);
	printf("输入年龄:");
	scanf("%s",&(s[count].age)); 
	printf("输入分数:");
	scanf("%f",&(s[count].score));
	//*/
	int i;
	for(i=0;i<count-1;i++)
	{
		printf("%s,%d,%.2f\n",s[i].name,s[i].age,s[i].score);
	}
	munmap(s,size+sizeof(struct stu));
	close(fd);
}

//makefile文件

map_write:map_write.c
    gcc map_write.c -o main
   


[pkm@linux ~/files]make map_write
gcc map_write.c -o main