Re: Failed to read a file
On Nov 5, 12:52 pm, Keith Willis <m...@privacy.net> wrote:
On Fri, 02 Nov 2007 06:44:41 -0700, James Kanze
<james.ka...@gmail.com> wrote:
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 >()) ) ;
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.
<snip>
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.)
OK, I've been playing with this and have a question. Your
reservation about using the seekg() and tellg() calls was
partly because the size of the file might not be representable
by an integral type.
Partially. Formally, there is no requirement of convertibility,
and no requirement that the integral values resulting from the
conversion will be meaningful in any traditional sense of the
word. Practically, at least under Windows and (probably most)
Unix, however, the only real problem will be the fact that the
size of the file typically isn't representable as an int.
(If you use long long, perhaps, you won't have a problem.)
But, if I
use this istreambuf_iterator method to read the data into my vector
vec, I then check the size of the data read using vec.size(), yes? But
vector::size() seems to return a size_type value, and that is an
unsigned integer type, at least according tohttp://www.cplusplus.com/refe=
rence/stl/vector/size.html, so I still
can't read files with a size larger than will fit in 32 bits...
Or am I missing something here?
Not really. The main difference is that if you overflow reading
into an std::vector, you get an exception (bad_alloc); if you
overflow converting to an int, you get some implementation
defined value which has little relationship to the actual size.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34