简体   繁体   中英

C++ ifstream reading X characters from a binary file into a string

I'm updating all my char* to string in my project and I'm got stuck at this part:

void Load(char* resourceName)
{
    _fileReader.seekg(0);
    while(_fileReader.tellg() < _FILE_SIZE)
    {
        int cResourceID = 0;
        char* cResourceName = new char[_MAX_RESOURCE_NAME];

        _fileReader.read((char*)&cResourceID, 4);
        _fileReader.read((char*)cResourceName, _MAX_RESOURCE_NAME);

        if(cResourceName == resourceName)
        {
            //Resource Found, do something
        }
    }
}

When I change to strings, I get:

void Load(string &resourceName)
{
    _fileReader.seekg(0);
    while(_fileReader.tellg() < _FILE_SIZE)
    {
        int cResourceID = 0;
        string cResourceName;

        _fileReader.read((char*)&cResourceID, 4);

        //I don't know how to do this:
        _fileReader.read((char*)cResourceName, _MAX_RESOURCE_NAME);

        //And nor this:
        if(cResourceName == resourceName)
        {
            //Resource Found, do something
        }
    }
}

Since I'm always reading _MAX_RESOURCE_NAME characters, my char* ends up like: "NAME !#$II#$II" (a bunch of uninitialized characters and/or empty spaces) and even the comparison (char* "NAME_ _ _" == string "NAME") fails.

Can I read X amount of characters into a string with ifstream as I do with char*?

And how can I clear the empty spaces/uninitialized characters from the file to compare the names?

edit: Forgot to add it's a binary file and I can't use std::getline()

After reading characters from file, you should add zero (0x0 or '\\0') after the last read character. Your buffer size should be big enough to accommodate zero termination.

In your case, reading directly into std::string may not be a very good idea. Read it to the buffer as it used to be, then assign char* buffer to string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM