std::ifstream::readsome not reading requested number of chars from stream.
Howind, Axel
howind@4com.de
Fri May 11 09:11:00 GMT 2007
Hi,
I'm having some trouble with std::ifstream. I would expect
std::ifstream::readsome to extract the requested number of bytes/chars
from the input stream unless end of stream is reached. However, reading
64 chars at a time, readsome only returns 63 chars when reaching 8192
bytes total. This does not occur with stringstreams. I can reproduce
this with different systems/compiler versions (gcc 3.4.6 on CentOS 4.4
and Redhat EL 4 as well as gcc 4.1/Ubuntu 7.04).
Seems like readsome just reads until the internal buffer is empty and in
this case returns less than the requested count of chars. I hope the
attached code makes clear what I mean. I would expect the loop only to
be exited when all data is read or an error occured.
Is this correct behaviour, or is this a bug in libstd++?
Thanks,
Axel
$ g++ bug.cpp -o bug
$ ./bug 0
n = 0
read 0 bytes total
tellg: 0
$ ./bug 123
n = 123
read 123 bytes total
tellg: 123
$ ./bug 8191
n = 8191
read 8191 bytes total
tellg: 8191
$ ./bug 8192
n = 8192
read 8191 bytes total
tellg: 8191
$ ./bug 10000
n = 10000
read 8191 bytes total # why not 10000 here?
tellg: 8191
$ wc -c test.txt
10000 test.txt
Code:
bug.cpp ----8<----8<----8<----
#include <iostream>
#include <fstream>
int main(int argc, char** argv)
{
int n = 1024;
if ( argc == 2 )
n = std::atoi(argv[1]);
std::cout << "n = " << n << "\n";
std::ofstream out ( "test.txt" );
for ( int i=0; i<n; i++ )
out.put ( '\0' );
out.close();
char buffer[64];
std::ifstream in ( "test.txt" );
int bytes, bytes_total = 0;
while ( ( bytes = in.readsome ( &buffer[0], 64 ) ) == 64 )
{
bytes_total += bytes;
}
bytes_total += bytes;
std::cout << "read " << bytes_total << " bytes total\n";
std::cout << "tellg: " << in.tellg() << "\n";
}
---->8---->8---->8---->8----
More information about the Libstdc++
mailing list