-
#include <sys/mman.h>
-
#include<stdio.h>
-
#include <unistd.h>
-
#include <sys/types.h>
-
#include <sys/stat.h>
-
#include <fcntl.h>
-
#define NAME_LEN 25
-
#define PERSON_CNT 5
-
#define RECORD_FILE_NAME "./people.data"
-
struct person
-
{
-
int id ;
-
int age ;
-
char *name;
-
};
-
-
int write_person_info_to_file(person people[], size_t size )
-
{
-
int fd = open(RECORD_FILE_NAME,O_RDWR|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR| S_IRWXG);
-
if(fd < 0)
-
{
-
return -1;
-
}
-
for(int i = 0 ; i<size ; ++i)
-
{
-
write(fd, (void*)&people[i], sizeof(people));
-
}
-
close(fd);
-
return 0 ;
-
}
-
int main(int argc, char** argv)
-
{
-
struct person people[PERSON_CNT]=
-
{
-
{10010,18,"LiLei"},
-
{10011,20,"HanMM"},
-
{10032,19,"WangJun"},
-
{10031,19,"CaoMeng"},
-
{10013,16,"XuXin"}
-
};
-
if(write_person_info_to_file(people,PERSON_CNT))
-
{
-
//error
-
fprintf(stdout,"save person infomation error \n");
-
return 1;
-
}
-
-
int fd = open(RECORD_FILE_NAME,O_RDWR|O_APPEND,S_IRUSR|S_IWUSR| S_IRWXG);
-
if(fd <0 )
-
{
-
fprintf(stdout,"open person infomation error \n");
-
return 1;
-
}
-
struct person *pperson = (struct person*)mmap(NULL,sizeof(person)*PERSON_CNT,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
-
if(pperson == MAP_FAILED)
-
{
-
//error accur
-
fprintf(stdout,"mmap function call error \n");
-
close(fd);
-
return 1 ;
-
}
-
close(fd);
-
struct person *blp = pperson;
-
for(int i= 0 ; i<PERSON_CNT ; ++i)
-
{
- //由于在保存的时候,将char*指针的值保存进文件,并不是保存指针的内容,因此在映射后,blp[i].name 的值是一个无效的指针,
-
//要访问该指针的值的时候就会引发coredown,此处只打印name的值
-
printf("id=[%d], name=[%p], age=[%d]\n",blp[i].id,&blp[i].name,blp[i].age);
-
-
}
-
munmap(pperson, sizeof(person)*PERSON_CNT);
-
-
return 0 ;
- }