A demo usging mmap() to read a file

本文提供了一个使用C语言实现的mmap内存映射文件的示例程序。该程序通过传递文件路径参数,打开文件并获取其大小,然后将文件映射到内存中,并读取文件内容输出到标准输出设备。最后释放映射内存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[cpp]  view plain copy
  1. #include <stdio.h>  
  2.   #include <sys/types.h>  
  3.   #include <sys/stat.h>  
  4.   #include <fcntl.h>  
  5.   #include <unistd.h>  
  6.   #include <sys/mman.h>  
  7.   
  8.   int main (int argc, char *argv[])  
  9.   {  
  10.           struct stat sb;  
  11.           off_t len;  
  12.           char *p;  
  13.           int fd;  
  14.   
  15.           if (argc < 2) {  
  16.                   fprintf (stderr, "usage: %s <file>\n", argv[0]);  
  17.                   return 1;  
  18.           }  
  19.   
  20.           fd = open (argv[1], O_RDONLY);  
  21.           if (fd == -1) {  
  22.                   perror ("open");  
  23.                   return 1;  
  24.           }  
  25.   
  26.           if (fstat (fd, &sb) == -1) {  
  27.                   perror ("fstat");  
  28.                   return 1;  
  29.           }  
  30.   
  31.           if (!S_ISREG (sb.st_mode)) {  
  32.                   fprintf (stderr, "%s is not a file\n", argv[1]);  
  33.                   return 1;  
  34.           }  
  35.   
  36.           p = mmap (0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);  
  37.           if (p == MAP_FAILED) {  
  38.                   perror ("mmap");  
  39.                   return 1;  
  40.           }  
  41.   
  42.           if (close (fd) == -1) {  
  43.                   perror ("close");  
  44.                   return 1;  
  45.           }  
  46.   
  47.           for (len = 0; len < sb.st_size; len++)  
  48.                   putchar (p[len]);  
  49.   
  50.           if (munmap (p, sb.st_size) == -1) {  
  51.                   perror ("munmap");  
  52.                   return 1;  
  53.           }  
  54.   
  55.           return 0;  
  56.   }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值