使用迭代器将部分文件流读入字符串 [英] Reading a partial file stream into a string using iterators
本文介绍了使用迭代器将部分文件流读入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我到目前为止所尝试的但没有成功:
This is what I have tried so far but with no success:
std::string ReadPartial( std::ifstream& _file, int _size )
{
std::istreambuf_iterator<char> first( _file );
std::istreambuf_iterator<char> last( _file );
std::advance( last, _size );
return std::string( first, last );
}
我知道如何读取整个文件。
I know how to read the whole file.
std::string Read( std::ifstream& _file )
{
std::istreambuf_iterator<char> first( _file );
std::istreambuf_iterator<char> last();
return std::string( first, last );
}
但这不是我想做的。我收到一个空字符串。如果我在调试器中查看第一个也是最后一个,即使在std :: advance之后它们指向相同的东西。
But this is not what i want to do. I'm getting an empty string. If I look at first and last in a debugger they point to the same thing even after the std::advance.
推荐答案
是你有什么特别的理由要使用迭代器吗?你可以一次读取字节:
Is there some particular reason you want to use iterators? You could just read the bytes in one go:
std::string s(_size, '\0');
_file.read(&s[0], _size);
如果你真的想用迭代器读取,你可以这样做:
If you really want to read using iterators, you could do this:
std::string ReadPartial( std::ifstream& _file, int _size )
{
std::istreambuf_iterator<char> first( _file );
std::istreambuf_iterator<char> last;
std::string s;
s.reserve(_size);
while (_size-- && first != last) s += *first++;
return s;
}
这篇关于使用迭代器将部分文件流读入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文