开发者

Easiest way to read a null terminate string with istream?

开发者 https://www.devze.com 2023-02-16 10:19 出处:网络
I have an ist开发者_开发问答ream 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 o

I have an ist开发者_开发问答ream 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.


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

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消