23,217
社区成员




//这样就行,这取决于test.txt文件中原始数据的大小,即重新拷贝的字符数小于等于原有字符数
fd = open("test.txt", O_RDWR | O_CREAT);
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define MAX_SIZE (32)
int main(void)
{
int fd;
char *buf;
struct stat statbuf;
if(stat("test.txt", &statbuf) == -1)
{
perror("fail to get stat");
exit(1);
}
fd = open("test.txt", O_RDWR | O_CREAT);
if(fd == -1)
{
perror("fail to open");
exit(1);
}
// test.txt文件已有内容小于MAX_SIZE时,扩大存储的字符数
if (ftruncate(fd, MAX_SIZE) != 0)
{
perror("fail to ftruncate");
exit(1);
}
buf = (char *)mmap(NULL, MAX_SIZE, PROT_WRITE, MAP_SHARED, fd, 0);
if(buf == MAP_FAILED)
{
perror("fail to mmap");
exit(1);
}
strcpy(buf, "China beijing");
if(munmap(buf, MAX_SIZE) == -1)
{
perror("fail to munmap");
exit(1);
}
close(fd);
return 0;
}