0

Here is the code I am trying with:

ifstream fileReader("server_data\\test2.jpg", ios::in | ios::binary);
char buffer[RESP_LENGTH];
memset(buffer, '\0', RESP_LENGTH);
if (fileReader.is_open())
{
    fileReader.seekg(0);
    fileReader.read(buffer, RESP_LENGTH);
    cout << buffer<<endl<<"Length: "<<strlen(buffer);
}
fileReader.close();

Its simply reading only first few bytes. Its also differing from file to file.

I am suspecting, probably its getting a character which evaluates to NULL and thus my length and string is getting small portion only?

Any Idea what is really happening and how to fix it?

Andrew Komiagin
  • 6,446
  • 1
  • 13
  • 23
Rana
  • 5,912
  • 12
  • 58
  • 91
  • 1
    I cannot tell that the `ifstream` read only few bytes from this. DO NOT use `strlen` to measure length of binary data. [istream::gcount](http://www.cplusplus.com/reference/istream/istream/gcount/) is useful to get the length read in this case. – MikeCAT Nov 01 '15 at 07:15

1 Answers1

2

The problem is not in the way you are reading in but in the way you are printing out.

If there's a \0 character this means end of string. So string operations (like strlen or printing to cout) will stop on that character (considering the string contained in your char* stops here), but it does not mean your char* array does not contain more characters....

Instead, you should do that:

cout << "Got " << fileReader.gcount() << "characters:";
for ( size_t i = 0; i != fileReader.gcount(); ++i )
    cout << buffer[i];

Then, you'll print all bytes you read, ignoring EOS and other special characters.

Note that special characters will not be printed correctly (See this post). But I guess your goal is not to print that binary content.

Community
  • 1
  • 1
jpo38
  • 20,821
  • 10
  • 70
  • 151
  • I would edit this to make it brutally clear to OP that the problem isn't with the reading in, but with the printing out. – user4581301 Nov 01 '15 at 07:38
  • True. Did that. Thanks – jpo38 Nov 01 '15 at 07:44
  • @jpo38 , thanks. Yes, so, I got the point. I am not concerned about printing it, but I am gonna send it over network. So, while copy the stream, I guess I will just need to use 'memcpy' with the buffer array size to copy everything regardless of which characters it contains, right? – Rana Nov 01 '15 at 07:58
  • 1
    Exactly, use gcount to know how many bytes you have to copy...and then you can accept the answer ;-) – jpo38 Nov 01 '15 at 08:43
  • `ostream::write` could be useful. – Alan Stokes Nov 01 '15 at 09:41