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.
#include <iostream>
#include <fstream>
#include <string.h>
struct Data
{
char word[64];
int i;
float f;
};
void print(void);
void read(void);
int main(void)
{
print();
read();
return 0;
}
void print(void)
{
Data myData;
strcpy(myData.word, "Hello World");
myData.i = 123;
myData.f = 3.14159;
// Can be opened in non-binary mode
std::ofstream output("file.txt");
output.write(reinterpret_cast<char*>(&myData), sizeof(myData));
output.close();
}
void read(void)
{
Data myData;
// This is opened in binary mode, but it didn't have to be
std::ifstream input("file.txt", std::ios::in | std::ios::binary);
input.read(reinterpret_cast<char*>(&myData), sizeof(myData));
std::cout << "Words: " << myData.word << '\n'
<< "Int : " << myData.i << '\n'
<< "Float: " << myData.f << '\n';
input.close();
}
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).