File manipulation problem

Started by
4 comments, last by Kheyas 12 years, 1 month ago
Hello once again!
I'm having some problems with a file stream. I Would be glad if somebody would help me smile.png

void SaveCharacter()
{
freopen("SaveGame.txt","w",stdout);
printf("%s\n",PlayerName);
printf("%d",PlayerExp);
//fclose(stdout);
}
void LoadCharacter()
{
freopen("SaveGame.txt","r",stdin);
scanf("%s\n",PlayerName);
scanf("%d",&PlayerExp);
//fclose(stdin);

I'm trying to use these 2 voids but it gets stuck when not using fclose and it gives a "handle is invalid" error when i use fclose. What could be the problem? [s]I will probably put all the code in pastebin and put the link later[/s]. Link (the voids are at the end. They are being used in the MainMenu() void.).
Advertisement
I'd guess that what you experience as being stuck is just that your program prints everything to the file instead of to the screen after the you have redirected the standard output to the file instead, and likewise trying to read any input from the saved file instead of the keyboard. And I would also guess that you cannot close the standard input and output handles, which is why it says the handle is invalid.

But that aside, why are you saving and loading via the standard input and output, and not just through a temporary file handle?
freopen closes the stream that gets replaced. stdin/stdout are no longer available.
Brother Bob - Can you give me an example code? I actually wanted to use files for this small game. To save & load characters. What other way could I use?
Open the file with fopen, and then use fprintf and fscanf to write and read.
Thanks! I got it finally.

This topic is closed to new replies.

Advertisement