Stream types in C++, how to read from IstringStrea

2019-09-08 08:53发布

i have a txt file that has millions of lines, each line has 3 floats, i read it using the following code :

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

and i works perfectly.

Now i want to try doing the same thing using Boost mapped files, so i do the following

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;

It compiles without any problem, but unfortunatly the X,Y,Z doesn't get the actual float numbers but just rubbish, and after one iteration the While is ended.

I probably doing something terribly wrong

How can i use and parse the data inside the memory mapped file ? i searched all over the internet and especially stack overflow and couldn't find any example.

I'm using windows 7 64 bit.

1条回答
一纸荒年 Trace。
2楼-- · 2019-09-08 09:01

Boost has a library made just for this purpose: 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';
}
查看更多
登录 后发表回答