user34537
user34537

Reputation:

Easiest way to read a null terminate string with istream?

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.

Upvotes: 7

Views: 7060

Answers (3)

Eugen Constantin Dinca
Eugen Constantin Dinca

Reputation: 9150

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

std::string strBuf;
std::getline( istream, strBuf, '\0' );

Upvotes: 13

Cameron
Cameron

Reputation: 98816

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.

Upvotes: 2

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30989

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.

Upvotes: 1

Related Questions