MrPickle5
MrPickle5

Reputation: 522

Trying to write a binary file, getting a text file

Trying to save my game by writing the game characters to a binary file. Unfortunately, my binary file is writing to the file as if it were a text file.

If I just instantiate a string and call the save function for the string, it writes to the binary file perfectly. However, if I call the same function from my CharacterSave function -- it just displays the file as a text file instead of a binary one.

The call hierarchy goes

  1. Character.Save() calls the string save, which writes to a binary file.

  2. Character.Save() calls the pouch (i.e. coinpouch) save, which writes to the binary file.

  3. Character.Save() calls the purse (i.e. backpack) save, which calls the dynamic array save, which writes the number of elements to a binary file and calls the potion save method, which calls the string save method.

EDIT: Solved the problem. I don't know how, but just making another .dat file solved it.

Call to save function

//Create instance of binary file object
std::ofstream file("game.dat", std::ios::out | std::ios::binary);

//Check if file is open
if(file.is_open())
{
    //Save character
    myFavoriteCharacter.Save(file);

    //Close the file
    file.close();
}
else
    std::cout << "\nFile did not open! " << std::endl;

Character save function

void Character::Save(std::ofstream & file)
{
    mName.Save(file);
    mPouch.Save(file);
    mPurse.Save(file);
}

String save function

void String::Save(std::ofstream & file)
{
    int tempLength = 0;
    tempLength = this->getLength();

    //Write the length of the string
    file.write(reinterpret_cast<char *>(&tempLength), sizeof(int));

    //Write the string
    file.write(reinterpret_cast<char *>(this->mStr), tempLength + 1);
}

CoinPouch (i.e. pouch) save function

void CoinPouch::Save(std::ofstream & file)
{
    file.write(reinterpret_cast<char *>(&mPlatinum), sizeof(int));
    file.write(reinterpret_cast<char *>(&mGold), sizeof(int));
    file.write(reinterpret_cast<char *>(&mSilver), sizeof(int));
    file.write(reinterpret_cast<char *>(&mCopper), sizeof(int));
}

DynamicArray save function

void DynamicArray::Save(std::ofstream & file)
{
    //Write the number of elements
    file.write(reinterpret_cast <char *>(&mElements), sizeof(int));

    //Save each element
    for(int i = 0; i < mElements; i++)
        mArray[i].Save(file);
}

Potion save function

void Potion::Save(std::ofstream & file)
{
    mName.Save(file);
    mDescription.Save(file);
    mPotency.Save(file);
    mCost.Save(file);
}

Upvotes: 1

Views: 2027

Answers (1)

MrPickle5
MrPickle5

Reputation: 522

Forced Visual Studio 2012 to open a new file called "game2.dat" and it worked. There is now a hex dump of my binary file, instead of the normal text file it was giving me. So weird and I do not really understand why this, but it did.

Thanks to those who read/responded.

Upvotes: 1

Related Questions