コマンドラインlinux端末アプリケーションを実現し、入力した指定ファイルをメモリにマッピングし、ファイル内容を印刷する

1473 ワード

実装コード:
#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......
"); return 0; } if( (fd = open(argv[1],O_RDONLY) ) < 0 ) { printf("Please Specified the correct FilePath......
"); return 0; } FileSize = get_file_size( argv[1] ); CharBuf= mmap(0, FileSize , PROT_READ, MAP_PRIVATE, fd,0); printf("File Content:%s
", 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.