在C中使用mmap写入内存。

巴黎

我想用来mmap()创建一个包含一些整数的文件。我想通过写入内存来写入此文件。我知道内存中的数据为二进制格式,因此文件中的数据也将为二进制。我可以mmap用于此目的吗?在哪里可以找到有关如何使用的良好资源mmap我没有找到好的入门手册。

雷克

这是一个例子:

#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的内存映射实现

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

C 套接字 - recv() 和 recvfrom() - 使用指定的模而不是顺序写入内存?

来自分类Dev

C编码::将结构写入内存块

来自分类Dev

使用gzipstream将压缩的xml数据写入内存流

来自分类Dev

写入内存地址

来自分类Dev

C / C ++-使用mmap的内存映射文件

来自分类Dev

写入内存映射的稀疏文件的漏洞

来自分类Dev

无法写入内存映射文件

来自分类Dev

硬件断点能够写入内存吗?

来自分类Dev

检测何时写入内存地址

来自分类Dev

CsvHelper未将数据写入内存流

来自分类Dev

以空字节开始写入内存

来自分类Dev

写入内存时C ++从Float到Hex的转换不正确

来自分类Dev

使用vb.net从另一个进程读取/写入内存

来自分类Dev

为什么写入内存比读取内存要慢得多?

来自分类Dev

在C中使用mmap或fscanf读取文件

来自分类Dev

无法在[whence]部分中使用1查找文件并同时写入内容

来自分类Dev

尝试通过子进程写入共享内存中的int(使用mmap)

来自分类Dev

在python中写入内存中的特定地址

来自分类Dev

如何创建和写入内存映射文件?

来自分类Dev

如何在Rust中写入内存映射地址?

来自分类Dev

cpp dll char指针分配,写入内存访问冲突

来自分类Dev

将复杂的结构写入内存映射文件

来自分类Dev

调用FindConnectionPoint时访问冲突写入内存

来自分类Dev

用于将struct成员写入内存的通用接口模式?

来自分类Dev

将 XSLT 输出写入内存中的多个对象

来自分类Dev

使用libpng 1.2将RGB图像缓冲区写入内存中的PNG缓冲区导致分段错误

来自分类Dev

在R中使用内存预分配的循环读取/写入

来自分类Dev

缓冲写入器在文本文件上写入内存垃圾

来自分类Dev

将属性写入内存缓存,而不写入Objectify中的数据存储区?

Related 相关文章

热门标签

归档