① vim write.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
struct student {
char name[20];
int id;
int age;
char sex;
};
int main(){
struct student stu[3] = {{"学生0", 1, 19, 'G'},
{"学生1", 2, 20, 'M'},
{"学生2", 3, 21, 'M'}};
int fd = open("./stu.dat",O_RDWR | O_CREAT,0644),i = 0,target;
for (; i < 3; ++i) {
write(fd,&stu[i],sizeof(stu[i]));
}
void *addr = mmap(NULL,sizeof(stu)*sizeof(stu[i]) , PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if(addr == MAP_FAILED){
perror("mmap failed");
return -1;
}
struct student *p = addr;
scanf("%d",&target);
printf("%s age =%d\n", (p+target)->name ,(p+target)->age);
munmap(addr, 56);
close(fd);
return 0;
}
②?gcc -o write write.c
③ ./write
4. 回车后输入 0-2 查询指定学生年龄
|