Mapping Example

本文介绍了一个使用C语言实现的简单程序,该程序通过内存映射的方式打开并读取文件内容。首先打开指定文件,然后获取文件大小,并检查是否为普通文件。接着将文件映射到内存中,读取其内容并打印,最后解除内存映射。

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

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


int mapFile(unsigned char *fileName, char **pFileBuf, int *pFileSize)
{
    struct stat sb;
    off_t len;
    char *p;
    int fd;


    fd = open (fileName, O_RDONLY);
    if (fd == -1)
    {
        perror ("open");
        return 1;
    }


    if (fstat (fd, &sb) == -1)
    {
        perror ("fstat");
        return 1;
    }


    if (!S_ISREG (sb.st_mode))
    {
        fprintf (stderr, "%s is not a file\n", fileName);
        return 1;
    }


    p = mmap (0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
    if (p == MAP_FAILED)
    {
        perror ("mmap");
        return 1;
    }


    if (close (fd) == -1)
    {
        perror ("close");
        return 1;
    }


    *pFileBuf = p;
    *pFileSize = sb.st_size;
    return 0;


}


int unmapFile(char *pFileBuf, int pFileSize)
{
    if (munmap (pFileBuf, pFileSize) == -1)
    {
        perror ("munmap");
        return 1;
    }
    return 0;
}




int main (int argc, char *argv[])
{
    off_t len;
    int size;
    char *p;
    int status = 0;


    if (argc < 2)
    {
        fprintf (stderr, "usage: %s <file>\n", argv[0]);
        return 1;
    }


    status = mapFile(argv[1], &p ,&size);
    if (status != 0)
    {
        return 1;
    }


    for (len = 0; len < size; len++)
        putchar (p[len]);


    status = unmapFile(p, size);
    if (status != 0)
    {
        return 1;
    }




    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值