/*********************************************************************************
|
* 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;
|
}
|