File I/o


Alex.

Retired
Joined
Aug 24, 2005
Messages
4,616
I need to save a single integer hiscore for this minigame I'm making in C and SDL. Here's a stripped down version of my code, which crashes the GP2X. Any help would be very much appreciated!

Code:
#include <stdio.h>

typedef struct {
	int hiscore;
} HISCORE;

HISCORE hiscore;

void gethiscore(void) {
	FILE* f;

	f = fopen("sqcolony", "rb");
	if(!f) return;

	fread(&hiscore,sizeof(HISCORE),1,f);
	fclose(f);
}

void savehiscore(int score) {
	if(score <= hiscore.hiscore) return;
	hiscore.hiscore = score;

	FILE* f;
	f = fopen("sqcolony", "wb");
	fwrite(&hiscore,sizeof(HISCORE),1,f);
	fclose(f);
}

int main(int argc, char **argv) {
	hiscore.hiscore = 0;
	int score = 0;

	gethiscore();

	//
	// gameloop
	//

	savehiscore(score);
}

- Alex
 
Alex. posted on Jul 8 2006 at 01:02 AM said:
I need to save a single integer hiscore for this minigame I'm making in C and SDL. Here's a stripped down version of my code, which crashes the GP2X. Any help would be very much appreciated!

Code:
#include <stdio.h>

typedef struct {
	int hiscore;
} HISCORE;

HISCORE hiscore;

void gethiscore(void) {
	FILE* f;

	f = fopen("sqcolony", "rb");
	if(!f) return;

	fread(&hiscore,sizeof(HISCORE),1,f);
	fclose(f);
}

void savehiscore(int score) {
	if(score <= hiscore.hiscore) return;
	hiscore.hiscore = score;

	FILE* f;
	f = fopen("sqcolony", "wb");
	fwrite(&hiscore,sizeof(HISCORE),1,f);
	fclose(f);
}

int main(int argc, char **argv) {
	hiscore.hiscore = 0;
	int score = 0;

	gethiscore();

	//
	// gameloop
	//

	savehiscore(score);
}

- Alex

You need to check f after:
f = fopen("sqcolony", "wb");

but otherwise it looks ok to me.
 
Last edited by a moderator:
"rb" and "wb" are modes normally used on Windows. Use "r" and "w" instead.
 
refractor: If I were to check it, how would it write it the first time the program rolls?

Dzz: That was it, thank you very much!

Thank you for solving my problem so fast! Many thanks!

- Alex
 
Alex. posted on Jul 8 2006 at 02:10 AM said:
refractor: If I were to check it, how would it write it the first time the program rolls?
You always need to check the return. If it can't open the file for writing it'll give you a null value and then you'll try and write to it anyway; that'd be bad. You can either pick it up and deal with it, or have you application crash out. Your choice. :)
 
Last edited by a moderator:
Back
Top