现在的位置: 首页 > 综合 > 正文

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

2013年01月27日 ⁄ 综合 ⁄ 共 802字 ⁄ 字号 评论关闭

实现代码:

#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.

【上篇】
【下篇】

抱歉!评论已关闭.