Re: Failed to read a file
On Nov 2, 2:05 pm, Keith Willis <m...@privacy.net> wrote:
On Fri, 02 Nov 2007 05:39:15 -0700, James Kanze
<james.ka...@gmail.com> wrote:
The simplest and surest way of reading all of a file into memory
is:
std::vector< char > v(
(std::istreambuf_iterator< char >( file )),
(std::istreambuf_iterator< char >()) ) ;
If you're unsure of the file size, you might want to wrap it in
a try block, catching bad_alloc.
James, could you elaborate on this mechanism for me?
It's just a more or less classical use of streambuf_iterator;
you can construct a vector with an iterator pair of any type.
All it does is read the entire file into the vector, in the
constructor.
I've been using the
file.seekg(0,ios::end);
file.tellg();
method for ages.
It seems to be a common idiom, however: file.tellg() returns a
streampos, which must be a class type (it is required to contain
multi-byte state, as well as the physical position in the file).
The standard requires an implicit conversion of this to
streamoff, but because streampos is a user defined type, this
must be a user defined conversion. The standard also requires
that streamoff be convertible into an integral type. However:
if streamoff is also a class type, the conversion of a streampos
to an integral type involves two user defined conversions, and
can't occur implicitly. Typically, streamoff is a typedef to
an integral type, so you're OK. But there are still two
potential problems: the mapping of the integral value of
streamoff may not be linear (not likely on a system modeling
files as byte streams, like Unix or Windows, but on more complex
systems, who knows), and the actual file size might not fit in
the target integral type. (On all of the systems I use, int is
32 bits, but files can be---and often are-- considerably bigger
than what will fit into 32 bits.)
How does your contruction work, and will a simple v.size()
give me the data size afterwards?
It works because it constructs a vector with the contents of the
file, by reading it. And v.size() will give you the exact value
of the number of bytes read.
--
James Kanze (GABI Software) mailto:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34