Saving data to a file in binary?

Started by
14 comments, last by andyb716 19 years, 5 months ago
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.
Advertisement
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.

anyway if you [google] the underlined you should find more info

Beginner in Game Development?  Read here. And read here.

 

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));
Yah thats what I have but it still show up as text and I can still change values.
you can edit a binary file in a text editor
ok I understand now, even though I save it in binary it still shows up as text, that sucks.
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?
the '\n' character shows up as a box, and all the other data shows up as readable characters.
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;}

This topic is closed to new replies.

Advertisement