tutorial 17: File I/O

991c178cbb1237d5e8e147aae5782cb9
0
TTTNL 101 Mar 16, 2013 at 01:53 c++

So as i’m doing part 17 of the devmaster tutorials, i encounter this piece of code:

FILE* f = fopen( "settings.txt", "r" );
fget( f, "xpos = %f", &x );
fclose( f );

When i paste this in Visual Studio 2010 it generates an error with “fget” because it is undefined. I searched through my entire project and “fget” is nowhere to be found, however i can find these:
-fgetwc
-fgetwchar
-fgetws
-fgetwc_nolock

and some others

i tried to google “fget C++” but it doesn’t even seem te exist. How can i work around this problem?

3 Replies

Please log in or register to post a reply.

A8433b04cb41dd57113740b779f61acb
0
Reedbeta 167 Mar 16, 2013 at 02:27

That’s weird. Indeed there is no such function as “fget” in C or C++. From the arguments being passed it looks like that should be fscanf. Try replacing the “fget” with “fscanf” and see how that works.

991c178cbb1237d5e8e147aae5782cb9
0
TTTNL 101 Mar 16, 2013 at 13:10

I’ve got it setup like this in my own game now (in my restart game function):

FILE* highscores;

highscores = fopen( "highscores.txt", "a" );
fscanf( highscores, "Highscore: %i", &currentHighscore );   //using "&currentHighscore" or "currentHighscore" doesn't make a difference, only "currentHighscore" gives me more 0's

printf( "%i\n", currentHighscore );

if ((gameObject.score != 0) && (gameObject.score > currentHighscore))
{
  fprintf( highscores, "Highscore: %i\n", gameObject.score);
}

fclose( highscores );

It doesn’t work yet, as you can see i print currentHighscore in the console as well to check if it works, but everytime it prints “0” twelve times (in the console). My highscores.txt file looks like this ( 500 is higher than the scores i get when testing):

Highscore: 500

and when i restart the game (in game) it still just prints the gameObject.score because it’s higher than 0 of course.

991c178cbb1237d5e8e147aae5782cb9
0
TTTNL 101 Mar 16, 2013 at 16:12

With the help of a few articles and a youtube video i’ve got it working:

highscores = fopen( "highscores.txt", "r" );
if (highscores != NULL) //if the file couldn't open it returns NULL so therefore this check
{
  fscanf( highscores, "Highscore: %i", &currentHighscore );
  fclose( highscores);
}
else
{
  printf("Could not open the file.\n");
}

printf( "%i\n", currentHighscore );

if ((gameObject.score != 0) && (gameObject.score > currentHighscore))
{
  highscores = fopen( "highscores.txt", "w" );  //if the score is higher than the highscore the file gets opened and cleared (w)
  if (highscores != NULL)
  {
   fprintf( highscores, "Highscore: %i\n", gameObject.score); //and it prints the new highscore
   fclose( highscores );
  }
  else
  {
   printf("Could not open the file.\n");
  }
}