1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/mman.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
struct stu{
char name[20];
int age;
float score;
};
main()
{
int fd;
struct stu *s;
struct stat st;
int size;
int count;
fd =open("newstu.dat",O_RDWR|O_CREAT|O_EXCL,0666);
if(fd==-1)
{
fd=("newstu.dat",O_RDWR);
if(fd==-1)
printf("error:%m\n"),exit(-1);
}
fstat(fd,&st);
size=(int)st.st_size;
count=size/sizeof(struct stu);
s=mmap(0,size+sizeof(struct stu),
PROT_READ|PROT_WRITE,
MAP_SHARED,fd,0);
printf("input your name:");
scanf("%s",s[count].name);
printf("input your age:");
scanf("%d",&(s[count].age));
printf("input your scores:");
scanf("%f",&(s[count].score));
munmap(s,sizeof(struct stu)+size);
close(fd);
}
|