dk13
dk13

Reputation: 1501

Copying binary file with C++ from an istream to an ostream not always correct

I've created a c++ app that uses poco libary FTPclientsession to download a binary file via ftp. In order to count the download progress I copy the file from an istream to an ostream byte by byte using the following code :

char c = 0;
    istream is;
    ostream os;
std::streamsize iter = 0;
is.get(c);
while (istr && ostr)
{
    ++iter;
    os.put(c);
    is.get(c);
}
return iter;

When I try to download a file of 1MB which in ftp server consists of 1048576 bytes (checked with stat command), most of times the iter never reaches this number but values less by one to three bytes from 1048573 to 1048575.
Very rarely it measures up to the correct size. I also checked the is.fail() and noticed that the cases where the measurement is not correct the failbit is set.
Is this a problem of the binary file , of bad connection with the server or problem with my code?

Upvotes: 1

Views: 375

Answers (1)

zett42
zett42

Reputation: 27766

Make sure to open both input and output streams in binary mode, otherwise it will perform line end conversions, that is replacing ASCII code 10 (\n) by { 13, 10 } (\r\n) depending on the platform.

std::ofstream out("data.bin", std::ios::binary);

You should also never use formatted input and output operations (i. e. operator >> and operator <<) when using binary streams. You are already using get() and put() so that should be fine.

Upvotes: 1

Related Questions