使用 Boost IOStreams 的 mmap:极简示例

以下 C++ 程序使用 boost::iostreams 内存映射文件,将其内容读入 std::string 并打印到 cout

它提供了如何使用 boost::iostreams 可移植 mmap 功能的最小示例。

mmap_example.cpp
//编译方式:g++ -o mmap mmap.cpp -lboost_iostreams
#include <boost/iostreams/device/mapped_file.hpp>
#include <iostream>
#include <string>
using namespace std;
using namespace boost::iostreams;

int main(int argc, char** argv) {
   //初始化内存映射文件
   mapped_file_source file(argv[1]);
   //将整个文件读入字符串
   string fileContent(file.data(), file.size());
   //打印字符串
   cout << fileContent;
   //清理
   file.close();
}

另请参见一个简单的 mmap() 只读示例


Check out similar posts by category: C/C++