• 13
• 18
• 19
• 27
• 9

# Saving data to a file in binary?

This topic is 4875 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I'm using c++ and the only way I could write and read in binary is the std::fstream. I've tried the FILE *file. and the std::ifstream and ostream and I couldn't get them to write in binary. What I need it for is to save scores for my game, If I use text then a player can go edit there scores and say they got a billion points on level one. What I have now is that is saves a couple scores correctly and then once I get the third score in there some of it gets erased or doesn't pull up properly. When I view the file its all on one line. Is that ok, because I try to put \n's to break the different scores. I seperate the name level and score with a blank space and then get the whole line with getline and the break apart the line with substrings. Maybe it putting the whole line in there and not finding line breaks. Can someone please tell me what file methods I should use and what ones can write binary? I've read on google they all can but I just can't get it to work, besides using fstream Thanks.

##### Share on other sites
well with C you would use fread() and wb or rb to make it binary.
and for C++ i think you need to use the qualifier ios::binary.

this is what i remember from a few years ago.

##### Share on other sites
std::ofstream fout("highscores.bin", std::ios::out | std::ios::binary); int highScores[10], numHighScores = 10; fout.write((char *)&numHighScores, sizeof(int)); fout.write((char *)highScores, numHighScores * sizeof(int));...std::ifstream fin("highscores.bin", std::ios::in | std::ios::binary); fin.read((char *)&numHighScores, sizeof(int)); fin.read((char *)highScores, numHighScores * sizeof(int));

##### Share on other sites
Yah thats what I have but it still show up as text and I can still change values.

##### Share on other sites
you can edit a binary file in a text editor

##### Share on other sites
ok I understand now, even though I save it in binary it still shows up as text, that sucks.

##### Share on other sites
Why would it show up as text? You can edit it in a text editer, but shouldn't it show up as misc. ASCII characters isntead of a string of human-readable numbers?

##### Share on other sites
the '\n' character shows up as a box, and all the other data shows up as readable characters.

##### Share on other sites
Write a test example that doesn't work and show us the code. The compilable code shouldn't need to be more than about 10 lines.

Pete

#include <fstream>#include <iostream>std::ofstream outFile;int main(){	char *String = "This is some text\n This is some more text.";	outFile.open("textfile.bin", std::ios::out | std::ios::binary);	outFile.write(String, strlen(String));	outFile.close();	return 0;}