c - Why does my program read an extra structure? -


I'm making a small console-based RPG to brush my programming skills. I am using structures to store character data. Things like your HP, power, maybe the inventory below the road. One of the important things that I should be able to do is to load and save the letters. This means that the reading and saving structures

I am just saving and loading a structure with the first name and last name, and I am trying to read it properly.

Here's my code to create a character:

  zero creator () {char namebuf [20]; Printf ("First name:"); If (zero! = Fgets (namespuff, 20, stdin)) {char * nlptr = strchr (namebuf, '\ n'); If (nlptr) * nlptr = '\ 0'; } Strcpy (party [nMember]. Fname, namebuf); Printf ("Last name:"); If (zero! = Fgets (namespuff, 20, stdin)) {char * nlptr = strchr (namebuf, '\ n'); If (nlptr) * nlptr = '\ 0'; } Strcpy (party [nMember] .lname, namebuf); / * Characters were created, now * save / save (party [nmber]); Printf ("\ n \ n"); LoadCharacter (); }  

and save it here. Factor:

  Save character from zero (character party) {FILE * fp; Fp = fopen ("data", "a"); Fwrite (& amp; party, sizeof (party), 1, fp); Fclose (fp); }  

and loadCharacter function

  zero loadCorrect () {FILE * fp; Character tempParty [50]; Int loop = 0; Int count = 1; Int read = 2; Fp = fopen ("data", "r"); While (Read! = 0) {read = fread (& tempParty [loop], sizeof (tempParty [loop]), 1, fp); Printf ("% d.% S% s \ n", count, tempParty [loop] .fname, tempParty [loop] .lname); Loop ++; Count ++; } Fclose (fpose); }  

The expected result of the program is that I input a name and last name like 'John Do', and it is added to the data file. Then it is read, maybe something like

  1 Jane Doi 2. John Doe  

and the program ends

However My output finally adds another blank structure.

  1 Jen Do 2. John Do 3. 3. I like to know why this is so. Keep in mind that I am reading the file until Fred gives a 0 indicating that this EOF has been killed.  

thanks :)

Change your loop:

  Whenever you write a file reading code (Fade (End TempPropi [Loop], Size (TempPorty [Loop]), 1, FP) {// Other stuff}  

Ask yourself this question- "What if I read an empty file?"


Comments

Popular posts from this blog

Eclipse CDT variable colors in editor -

AJAX doesn't send POST query -

wpf - Custom Message Box Advice -