实现一个命令行linux终端应用程序,把输入的指定文件,映射到内存中,并打印出文件内容

实现代码:

#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/fcntl.h>

unsigned long get_file_size(const char *path)  
{  
    unsigned long filesize = -1;      
    struct stat statbuff;  
    if(stat(path, &statbuff) < 0)
    {  
        return filesize;  
    }
    else
    {  
        filesize = statbuff.st_size;  
    } 
 
    return filesize;  
}  


int main(int argc, char **argv)   
{  
    int fd,i;
    char *CharBuf;
    int FileSize;
    if ( NULL == argv[1] )
    {
        printf("Please Input FilePath......\n"); 
        return 0;  
    }
    if( (fd = open(argv[1],O_RDONLY) ) < 0 ) 
    {
       printf("Please Specified the correct FilePath......\n");
       return 0;
    }
    FileSize = get_file_size( argv[1] );

    CharBuf= mmap(0, FileSize , PROT_READ, MAP_PRIVATE, fd,0);  
    printf("File Content:%s\n", CharBuf );
}  



测试结果:(改程序可执行名字设为mmap-test:  )

1.编译程序:

$ gcc -g -o mmap-test mmap-test.c

2,运行程序 不输入文件名

.$./mmap-test

Please Input FilePath......

3. 输入正确文件名

$./mmap-test Danny.txt

File Content:I believe myself in depth and I will succeed eventually.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值