实现代码:
#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.