7

I have an istream and i need to read exactly a specific amount of bytes BUT i dont know the length of it. It is null terminated. I was thinking i could either 1) Write a loop and read one byte at a time 2) Tell it to return me a buffer or string which starts now until a certain byte (0 in this case). or 3) Read into a buf exactly one byte at a time and check it for 0 and append it to string if it isnt.

The 3rd i know i can do but the other 2 sounds like it may be possible with istream (its a filestream in this case). I am still reading documentation for istream. Theres a lot.

3 Answers3

13

Since you don't know the length of it the simplest would be:

std::string strBuf;
std::getline( istream, strBuf, '\0' );
Eugen Constantin Dinca
  • 8,994
  • 2
  • 34
  • 51
  • You actually need to use '\0' instead of 0. Otherwise your code doesnt work as expected. It too me a bit to figure that out –  Mar 14 '11 at 04:30
  • @acidzombie24: There should be no difference (the ASCII value of `\0` is 0) unless in your library there is an overload for `getline()` that accepts an `int` as a third parameter. What error were you getting? – Cameron Mar 14 '11 at 04:55
  • I'm sure it has to do with a int VS char overload. Here is an example http://codepad.org/YRDKVmNs vs your int example http://codepad.org/KwIjtaof –  Mar 14 '11 at 05:21
  • @acidzombie: Huh, it seems like it can't auto-convert `int` to `char`, which I guess makes sense in the general case since they're of different sizes. Good to know! My theory about the overload is totally wrong. – Cameron Mar 14 '11 at 05:26
  • @acidzombie, @cameron: from the "doesn't work as expected" I thought that it had problems at runtime. Tnx for the correction. – Eugen Constantin Dinca Mar 14 '11 at 05:56
2

Number 2) is possible using the getline method of istream:

std::istream is = ...;

const int MAX_BUFFSIZE = 512;
char buffer[MAX_BUFFSIZE];

is.getline(buffer, MAX_BUFFSIZE, '\0');    // Get up to MAX_BUFFSIZE - 1 bytes until the first null character (or end of stream)

Note that this removes the delimiter (null character) from the input stream, but does not append it to the buffer (this is the difference between getline() and get() for this example). However, the null character is automatically appended to the buffer; so, the last byte will contain the null character, but it will be removed from the stream.

Cameron
  • 96,106
  • 25
  • 196
  • 225
1

It looks like the overload:

istream& get (char* s, streamsize n, char delim ); 

from http://www.cplusplus.com/reference/iostream/istream/get/ will solve your problem; put '\0' as delim. There is also a version (shown at http://www.cplusplus.com/reference/string/getline/) that will return an std::string.

Jeremiah Willcock
  • 30,161
  • 7
  • 76
  • 78