【问题标题】:When using Boost::mapped_file, why does the size of the file appear to cap at 65,356 bytes? [closed]使用 Boost::mapped_file 时,为什么文件的大小似乎上限为 65,356 字节? [关闭]
【发布时间】:2020-11-20 00:39:40
【问题描述】:

对于我的程序,我正在使用 boost::mapped_file 来内存映射我想要访问以用于模式检测算法的文件。为了测试映射文件的构造,以及我的算法的以下执行,我一直在通过指定我想要的文件大小、创建文件并用随机字符填充它来测试文件的映射,然后映射该文件。问题是我遇到了一个奇怪的错误,我不太确定发生了什么。

我得到的错误是,一旦我的文件达到 size=65,536 字节,当尝试使用 boost::mapped_file_source::size() 方法时,返回值为 0。我尝试的任何文件大小在此之后使用的只是 65,536 的增量版本,这意味着文件 size=65,538 返回的大小为 2。

我很好奇这是否与映射文件的对齐有关,我看到它提到了here。但是,当我调用 boost::mapped_file_source::alignment() 方法时,它返回了 4096,我不明白。对齐是什么意思,它是如何解决这个问题的?

另外,为什么 boost::mapped_file_source::size() 在 file_size>65,536 bytes 时返回 0?我知道 65,536 等于对齐值 (4096) * 16,但我不明白为什么。

【问题讨论】:

  • 65536 是 2^16,因此您可以在 std::fpos 为 16 位宽的平台上运行,或者在未显示的代码中的其他地方对 unsigned short 进行一些截断。
  • @dxiv 你完全正确,我将大小截断为无符号短。 short unsigned int size=mappedfile->mapfile.size();

标签: c++ boost memory-alignment memory-mapped-files


【解决方案1】:

您应该显示相关代码。 Docs

 explicit mapped_file_source( const std::string& path,
                             size_type length = max_length,
                             boost::intmax_t offset = 0 );

具体来说,如果未指定length,它将使用文件大小。

Boost IOStreams 没有您描述的限制,您可以轻松展示:

Live On Coliru

#include <boost/iostreams/device/mapped_file.hpp>
#include <iostream>
#include <sys/stat.h>
#include <fcntl.h>

static constexpr auto PATH = "path";

void test(std::size_t length) {
    int fd =::creat(PATH, 0600);
    if (::ftruncate(fd, length) || ::close(fd))
        ::perror("whoops");

    boost::iostreams::mapped_file_source m(PATH);
    std::cout
        << m.size() << " = "
        << std::hex << std::showbase << m.size() << "\n";
}

int main() {
    test(0XFFFF);
    test(0X1FFFF);
    test(0X2FFFF);
}

打印

65535 = 0xffff
0x1ffff = 0x1ffff
0x2ffff = 0x2ffff

【讨论】:

  • 是的,谢谢你,我在不知不觉中将文件的大小截断为无符号短,这就是截断的来源。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多