2013-07-03 26 views
0

我有了数百万行的txt文件,每行有3辆彩车,我读它使用下面的代码:C++中的流类型,如何从IstringStream读取?

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并没有得到实际的浮点数,但只是垃圾,经过一次迭代后,结束。

我可能做一些可怕的错误

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

我使用的是Windows 7 64位。

+1

由于您使用升压已经,为什么不把它简单,使用[mapped_file_source](http://www.boost.org/ doc/libs/release/libs/iostreams/doc/classes/mapped_file.html#mapped_file_source)从boost.iostreams? (同时,'while(!file.eof())'在任何情况下都是错误的) – Cubbi

+0

我很兴奋,应该如何使用它,以及如何解析使用它的浮点数? – OopsUser

回答

3

升压刚刚为此目的而库: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'; 
} 
+0

谢谢,奇怪的是,使用琐碎的ifstream阅读并不会更快。也许我错过了一些东西,或者str填充x,y,z的解析非常缓慢...... – OopsUser

+0

@OopsUser这是一个单遍文件,从头到尾。内存映射几乎没有什么收获(它会在智能操作系统上节省一个内存到内存的拷贝) – Cubbi