本文介绍了在C中使用mmap写入内存.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用mmap()创建一个包含一些整数的文件.我想通过写入内存来写入此文件.我知道内存中的数据是二进制格式,因此文件中的数据也将是二进制格式. 我可以为此目的使用mmap吗?在哪里可以找到有关如何使用mmap的良好资源?我没有找到好的入门手册.
I want to use mmap() to create a file containing some integers. I want to write to this file by writing to memory. I know that the data in memory is binary format and hence the data in file will also be in binary. Can I use mmap for this purpose? where can I find good resources on how to use mmap? I didn't find a good manual to start with.
推荐答案以下是示例:
#include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> /* mmap() is defined in this header */ #include <fcntl.h> void err_quit(char *msg) { printf(msg); return 0; } int main (int argc, char *argv[]) { int fdin, fdout; char *src, *dst; struct stat statbuf; int mode = 0x0777; if (argc != 3) err_quit ("usage: a.out <fromfile> <tofile>"); /* open the input file */ if ((fdin = open (argv[1], O_RDONLY)) < 0) {printf("can't open %s for reading", argv[1]); return 0; } /* open/create the output file */ if ((fdout = open (argv[2], O_RDWR | O_CREAT | O_TRUNC, mode )) < 0)//edited here {printf ("can't create %s for writing", argv[2]); return 0; } /* find size of input file */ if (fstat (fdin,&statbuf) < 0) {printf ("fstat error"); return 0; } /* go to the location corresponding to the last byte */ if (lseek (fdout, statbuf.st_size - 1, SEEK_SET) == -1) {printf ("lseek error"); return 0; } /* write a dummy byte at the last location */ if (write (fdout, "", 1) != 1) {printf ("write error"); return 0; } /* mmap the input file */ if ((src = mmap (0, statbuf.st_size, PROT_READ, MAP_SHARED, fdin, 0)) == (caddr_t) -1) {printf ("mmap error for input"); return 0; } /* mmap the output file */ if ((dst = mmap (0, statbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fdout, 0)) == (caddr_t) -1) {printf ("mmap error for output"); return 0; } /* this copies the input file to the output file */ memcpy (dst, src, statbuf.st_size); return 0; } /* main */从这里 另一个Linux示例 Windows实现 进行内存映射.
From Here Another Linux example Windows implementation of memory mapping.
更多推荐
在C中使用mmap写入内存.
发布评论