如何从 fstream 中准确读取 128 个字节到字符串对象中?
我编写了一些代码来读取文件的前 128 个字节并打印它,然后读取文件的最后 128 个字节并打印它。最后一部分有效,因为您可以轻松迭代到 EOF,但如何从前面准确获取 128 个字节?下面的代码不起作用,因为您无法将 128 添加到 ifstream 迭代器,它不可索引,只能递增(看起来)。
当然,我可以创建一个迭代器并 *++ 128 次,但必须有一个简单的单行方法来完成它,对吗?
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char **argv)
{
std::ifstream ifs ("input.txt",std::ifstream::in | std::ifstream::binary);
if (ifs.good())
{
// read first 128 bytes into a string
ifs.seekg(0,std::ifstream::beg);
std::string first128((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>(ifs))+128);
std::cout << first128 << std::endl;
// read last 128 bytes into a string
ifs.seekg(-128,std::ifstream::end);
std::string last128((std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>());
std::cout << last128 << std::endl;
return 0;
}
return 1;
}
char buffer[129];
ifs.read (buffer,128);
buffer[128] = '\0';
first128 = buffer;
那么这个怎么样:
template <typename Itr, typename Out>
void copy_n(Itr it, size_t count, Out out)
{
for(size_t i=0;i<count;++i)
out = *it++;
}
...
std::string first128;
std::istreambuf_iterator<char> it(ifs);
copy_n( it, 128,
std::back_inserter<std::string>(first128) );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)