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

Stream types in C++, how to read from IstringStream?

本文关键字:读取 IstringStream 类型 C++      更新时间:2023-10-16

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

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没有得到实际的浮点数,只是垃圾,一次迭代后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';
}