How to scan file bytes using istreambuf_iterator<unsigned char> iit(f);
Phil Nicolletti posted this code to load a section of a text file given an open fstream, starting and ending points:
Code:
/// Suggested by Phil Nicolleti : http://www.codeguru.com/forum/showthread.php?t=473898
/// Modified by Mike Pliam August 19, 2014 for single byte file streams.
vector<char> GetBytes(ifstream &f, long ustart, long uend)
{
vector<char> vb;
const long nsz = (uend-ustart)/2;
vb.resize(nsz); //vb = 0x00;
if(!f.is_open()) { _RPT0(0, "No stream available in GetBytes.\n"); return vb; }
if(ustart < 0 || uend < ustart) return vb;
f.clear();
f.seekg(ustart);
istreambuf_iterator<char> iit(f);
//std::istreambuf_iterator<char> iit (std::cin.rdbuf()); // stdin iterator
for(int ul = 0; ul < nsz; ul++)
{
vb[ul] = *iit++;
}
return vb;
}// GetBytes(ifstream &f, long ustart, long uend)
But now I want to load a section of bytes (unsigned char) rather than char. Unfortunately, I cannot get to cooperate:
Code:
istreambuf_iterator<unsigned char> iit(f);
.
Error is:
Quote:
error C2664: 'std::istreambuf_iterator<_Elem>::istreambuf_iterator(std::basic_streambuf<_Elem,_Traits> *) throw()' :
cannot convert parameter 1 from 'std::ifstream' to 'std::basic_streambuf<_Elem,_Traits> *'
I need bytes, not chars. Help appreciated.
Re: How to scan file bytes using istreambuf_iterator<unsigned char> iit(f);
Quote:
Originally Posted by Mike Pliam
I need bytes, not chars.
char, signed char and unsigned char can all be used to store "bytes", but the latter tends to be the best option when you will do things like bit shifting.
Quote:
Originally Posted by Mike Pliam
But now I want to load a section of bytes (unsigned char) rather than char. Unfortunately, I cannot get to cooperate:
You may need to use std::istream_iterator instead of std::istreambuf_iterator, but I'm not sure how that might affect the efficiency. Alternatively, you could switch the std::vector<unsigned char>, but leave it as std::istreambuf_iterator<char> since whether char is signed or unsigned, the conversion to unsigned char will be safe.