使用fstream加载二进制文件 [英] Load binary file using fstream
本文介绍了使用fstream加载二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用 fstream
以以下方式加载二进制文件:
I'm trying to load binary file using fstream
in the following way:
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
basic_fstream<uint32_t> file( "somefile.dat", ios::in|ios::binary );
vector<uint32_t> buffer;
buffer.assign( istream_iterator<uint32_t, uint32_t>( file ), istream_iterator<uint32_t, uint32_t>() );
cout << buffer.size() << endl;
return 0;
}
但它不工作。在Ubuntu它崩溃与 std :: bad_cast
异常。在MSVC ++ 2008它只打印0。
But it doesn't work. In Ubuntu it crashed with std::bad_cast
exception. In MSVC++ 2008 it just prints 0.
我知道我可以使用 file.read
加载文件,我想使用迭代器和 operator>>
加载文件的部分。那可能吗? 为什么上面的代码不起作用?
I know that I could use file.read
to load file, but I want to use iterator and operator>>
to load parts of the file. Is that possible? Why the code above doesn't work?
推荐答案
-
istream_iterator 要
basic_istream
作为参数。 - 不能重载<$ c $ c>
- 定义全局
运算符> ;>
会导致与类成员operator>>
之间的编译时冲突。 - 为
uint32_t
类型指定basic_istream
。但是对于专业化,你应该重写basic_istream
类的所有功能。您可以定义虚拟类x
并专门化basic_istream
,如下面的代码:
istream_iterator
wantsbasic_istream
as argument.- It is impossible to overload
operator>>
insidebasic_istream
class. - Defining global
operator>>
will lead to compile time conflicts with class memberoperator>>
. - You could specialize
basic_istream
for typeuint32_t
. But for specialization you should rewrite all fuctionons ofbasic_istream
class. Instead you could define dummy classx
and specializebasic_istream
for it as in the following code:
using namespace std;
struct x {};
namespace std {
template<class traits>
class basic_istream<x, traits> : public basic_ifstream<uint32_t>
{
public:
explicit basic_istream<x, traits>(const wchar_t* _Filename,
ios_base::openmode _Mode,
int _Prot = (int)ios_base::_Openprot) : basic_ifstream<uint32_t>( _Filename, _Mode, _Prot ) {}
basic_istream<x, traits>& operator>>(uint32_t& data)
{
read(&data, 1);
return *this;
}
};
} // namespace std
int main()
{
basic_istream<x> file( "somefile.dat", ios::in|ios::binary );
vector<uint32_t> buffer;
buffer.assign( istream_iterator<uint32_t, x>( file ), istream_iterator<uint32_t, x>() );
cout << buffer.size() << endl;
return 0;
}
这篇关于使用fstream加载二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文