0

I am making a simple game using c programming for our project. The information of players (Player number such as 1 2 or 3, Name of player, and score) is stored in a text file through structures. I want to "load" the information of the previous players before the game starts so the current player knows what his/her player number is by getting the player numbes from the file and immediately printing it out. I am using the while(!feof(fp)) but I'm getting trouble because it only prints the first player number. Please help me.

while(!feof(fp)) {
fp = fopen("scores.txt","a+");
fscanf(fp, "%i \n", &p[load].nth);
printf ("Loading player no. %i...\n", p[load].nth);
fscanf(fp, "%s \n", p[load].name);
fscanf(fp, "%i \n", &p[load].score);
load++;
}

count=load;
p[count].nth=count;
printf("You are player no. %i", p[count].nth);

1 Answers1

4

Your code has a few errors.

  1. You can't use feof(fp) before opening the file and assigning the value to fp. That's undefined behavior.
  2. You shouldn't use "a+" mode when opening to read, that means "read with append" which is not what you're after.
  3. You shouldn't use feof() like that anyway: it's purpose is not to figure out when to stop reading, it's for figuring out after the fact why reading failed.
  4. You don't need & when the argument is a string.

It also seems likely that there is some off-by-one indexing problem with the way you handle count.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • 1
    Also, `"a+"` mode positions the read/write cursor at the end of the file. Here, `"r"` should be the mode to use. – DarkDust Mar 24 '14 at 08:10