内存映射写文件失败问题,请看下

问下下面使用内存映射写文件的代码为什么写不了文件,多谢

#include 
#include 
#inlcude 
#inlcude 
#include 
#include 
#include 
#include 
#include 

using namespace std;

int main()
{
 int fd = open("Data.txt", O_RDWR | O_CREAT);
  int size = lseek(fd, 0, SEEK_END);
  unsigned int pageSize = 4096;
  fd = (fd + pageSize  - 1) & ~(pageSize - 1);
  cout << "size = " << size << ", fd = " << fd <void *ptr = mmap(NULL, 1024, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, fd, 0);
  if(ptr == MAP_FAILED)
  {
    perror("mmap");
    return 0;
  }
  strcpy((char *)ptr, "adslfjaslkjfdlkasfd");
  char buf[64] = {0};
  strcpy(buf, (char *)ptr);
  printf("str = %s\n", buf);

  munmap(ptr, 1024);
  return 0;
}


你的文件描述符 fd 被重新赋值为内存映射中的地址,这导致了将字符串写入内存映射区域而不是写入文件。

另外,在进行内存映射时没有使用文件大小作为映射长度。如果需要将字符串写入文件,则需要在内存映射时使用文件大小作为映射长度,并将映射区域的地址指向文件开始位置,而不是使用 MAP_ANONYMOUS 创建匿名内存映射。

以下是修改后的代码:

#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main()
{
    int fd = open("Data.txt", O_RDWR | O_CREAT, 0666);
    int size = lseek(fd, 0, SEEK_END);
    unsigned int pageSize = 4096;
    size = (size + pageSize - 1) & ~(pageSize - 1);
    cout << "size = " << size << ", fd = " << fd <<endl;
    void *ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if(ptr == MAP_FAILED)
    {
        perror("mmap");
        return 0;
    }
    close(fd);
    strcpy((char *)ptr, "adslfjaslkjfdlkasfd");
    char buf[64] = {0};
    strcpy(buf, (char *)ptr);
    printf("str = %s\n", buf);

    msync(ptr, size, MS_SYNC); //同步内存映射区域到文件
    munmap(ptr, size);
    return 0;
}

修改后的代码在打开文件后,将原始文件描述符 fd 传递给 mmap() 函数,再进行内存映射。使用文件大小作为映射长度,并将映射区域的地址指向文件开始位置。

最后,使用 msync() 函数将映射区域的数据同步到文件中,最终实现将字符串写入文件中。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^