Just wondering how to implement a highscore feature into a small game using binary. I have done it with txt before but want to try binary. I have been told that it is almost the same as txt so I did the following functions but it is unable to close down, so either unable to write to it or I made the binary file wrong or my code is completely wrong, any help would be appreciated, thanks
1 2 3 4 5 6 7 8 9 10 11 12 13
void Score::ReadScore()
{
//Open the file for (r)eading
FILE* pFile = fopen("HighScores.bin", "r");
if (pFile != NULL)
{
char acWords[1024];
fgets(acWords, 1024, pFile); //gets a string, max length 1024
m_iHighScore = atoi(acWords);
}
fclose(pFile);
}
About to say the same thing. If you're using member functions, you might as well use fstream.
As far as I've seen, the only reason to open a file in binary mode is if you need to read single characters where those characters might set the EOF bits on the istream.
The read()/write() functions still work with a non-binary open mode. They do read/write in binary as well. Read() and Write() expect char*, but you can cast your data types. Also note that data in a struct/class is stored contiguously, making this a very easy way to write and read data.
It gets tricky though. If the class/struct had a pointer variable, then these functions will only read/write the pointer's value (not the data in the whatever it points to).