Re: Failed to read a file
On Nov 2, 10:05 am, "Jim Langston" <tazmas...@rocketmail.com> wrote:
"Matrixinline" <anup.kata...@gmail.com> wrote in message
[...]
You open the file, get the position. The position at this
point is 0. Did you mean to add the line
file.seekg (0, std::ios::end);
before the size = file.tellg();?
This may work on a lot of systems, but formally, there's no
guarantee that the results of tellg() can be implicitly
converted to an integral type, and there's even less of a
guarantee that they represent the number of bytes in the file
between the current position and the beginning of the file; a
system can use any sort of magic encoding it wants. (In
practice, of course, it probably works under Unix, and for files
opened in binary under Windows. Provided the files aren't too
big.)
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 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