我有一个包含数百万行的 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/