c++ - C++ 中的流类型,如何从 IstringStream 中读取?

标签 c++ boost memory-mapped-files istringstream

我有一个包含数百万行的 txt 文件,每行有 3 个 float ,我使用以下代码读取它:

ifstream file(path)
float x,y,z;
while(!file.eof())
  file >> x >> y >> z;

我工作得很好。

现在我想尝试使用 Boost 映射文件做同样的事情,所以我执行以下操作

string filename = "C:\\myfile.txt";
file_mapping mapping(filename.c_str(), read_only);
mapped_region mapped_rgn(mapping, read_only);
char* const mmaped_data = static_cast<char*>(mapped_rgn.get_address());
streamsize const mmap_size = mapped_rgn.get_size();

istringstream s;
s.rdbuf()->pubsetbuf(mmaped_data, mmap_size);
while(!s.eof())
  mystream >> x >> y >> z;

它编译没有任何问题,但不幸的是,X、Y、Z 没有得到实际的 float ,而是垃圾,并且在一次迭代后 While 结束。

我可能做错了什么

我如何使用和解析内存映射文件中的数据? 我搜索了整个互联网,尤其是堆栈溢出,但找不到任何示例。

我正在使用 windows 7 64 位。

最佳答案

Boost 有一个专门为此目的制作的库:boost.iostreams

#include <iostream>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
namespace io = boost::iostreams;

int main()
{
    io::stream<io::mapped_file_source> str("test.txt");
    // you can read from str like from any stream, str >> x >> y >> z
    for(float x,y,z; str >> x >> y >> z; )
        std::cout << "Reading from file: " << x << " " << y << " " << z << '\n';
}

关于c++ - C++ 中的流类型,如何从 IstringStream 中读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17449437/

相关文章:

c++ - 在类 C++ 中初始化引用成员

c++ - Linux 中的套接字

c++ - C++在目录中对文件名进行排序

c++ - 我怎样才能进一步专门化这个模板的想法?

c# - 具有单个编写器的 MemoryMappedFile 是否需要同步

c++ - 如何在 C++ 中打开具有相对路径的文件?

c++ - 返回 map 循环的问题

c++ - Shared_ptr 在创建 boost 线程时从未被释放

c# - MemoryMappedFiles 找不到路径的一部分

c++ - 内存映射文件中对象的排序