APUE course source code
guowenxue
yesterday 7b55c92f8d1401a93c8fd8e342da271dce742000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  mmap_file.c
 *    Description:  This file Memory Map(file) example program
 *
 *        Version:  1.0.0(11/10/2025)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "11/10/2025 12:44:56 PM"
 *
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
 
int main(void)
{
    int             fd, rv=0;
    struct stat     st;
    char            *mapped;
    char            *file = "test.txt";
 
    fd = open(file, O_RDWR);
    if (fd < 0)
    {
        printf("open \"%s\" failure: %s\n", file, strerror(errno));
        return 1;
    }
 
    /* 获取文件大小 */
    if (fstat(fd, &st) == -1)
    {
        printf("fstat failure %s\n", strerror(errno));
        rv = 2;
        goto cleanup;
    }
 
    /* 将文件映射到内存 */
    mapped = mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (mapped == MAP_FAILED)
    {
        printf("mmap failure %s\n", strerror(errno));
        rv = 4;
        goto cleanup;
    }
 
    /* 修改文件内容 */
    printf("Original content: %s\n", mapped);
    strcpy(mapped, "Hello mmap!\n");
    printf("Modify   content: %s\n", mapped);
 
    /* 解除映射并关闭文件 */
    munmap(mapped, st.st_size);
 
cleanup:
    close(fd);
    return 0;
}