linux c 通过内存映射,操作文件
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
/*
MAP_SHARED: 映射区的数据直接反映到文件中
MAP_PRIVATE:映射区的数据不会反映到文件中
*/
struct msg
{
char name[20];
int age;
};
int main()
{
int fd = open("obj",O_RDWR|O_CREAT,0664);
if(fd == -1) perror("open"),exit(-1);
int ret = ftruncate(fd,sizeof(struct msg)*20);
if(ret == -1) perror("ftruncate"),exit(-1);
void* pp = mmap(NULL,sizeof(struct msg),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
struct msg* p =pp;
for(int i = 0;i<20;i++)
{
strcpy(p->name,"袁苏东! ");
p->age= 10;
p++;
}
munmap(pp,sizeof(struct msg)*20);
close(fd);
return 0;
}
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
/*
MAP_SHARED: 映射区的数据直接反映到文件中
MAP_PRIVATE:映射区的数据不会反映到文件中
*/
struct msg
{
char name[20];
int age;
};
int main()
{
int fd = open("obj",O_RDWR|O_CREAT,0664);
if(fd == -1) perror("open"),exit(-1);
int ret = ftruncate(fd,sizeof(struct msg)*20);
if(ret == -1) perror("ftruncate"),exit(-1);
void* pp = mmap(NULL,sizeof(struct msg),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
struct msg* p =pp;
for(int i = 0;i<20;i++)
{
strcpy(p->name,"袁苏东! ");
p->age= 10;
p++;
}
munmap(pp,sizeof(struct msg)*20);
close(fd);
return 0;
}
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇: linux c实现文件复制
- 下一篇: php中关联数组的定义方式