Search code examples
c++fstream

Reading a null terminated string from a binary file c++


As the title says I'm trying to read a null terminated string from a binary file.

std::string ObjElement::ReadStringFromStream(std::ifstream &stream) {
    std::string result = "";
    char ch;
    while (stream.get(ch) != '\0') {
        result += ch;
    }
    return result; }

My null character is '\0'

But any time I call the method it reads to the end of the file

std::ifstream myFile(file, std::ios_base::in | std::ios_base::binary);
myFile.seekg(startByte);

this->name = ObjElement::ReadStringFromStream(myFile);

Any idea what I'm doing wrong here?


Solution

  • istream::get(char &) returns a reference to the istream, not the character read. You can either use the istream::get() variant like so:

    while ((ch = stream.get()) != '\0') {
        result += ch;
    }
    

    Or use the returned stream reference as a bool:

    while (stream.get(ch)) {
        if (ch != '\0') {
            result += ch;
        } else {
            break;
        }
    }