I am suppose to write a program that can save a list of names and its relevant info(into a structure). However, i have problem retrieving the "name" datas out when i open the program again.Here's a summary of what i wrote.PLEASE TAKE NOTE OF LINE A AND LINE B.
Code:
/* structure declaration */
typedef struct {
char marker;
char id;
char name[21];
}data;
/* function protype */
void quit(data seat[12]);
main(void)
{
/* declare variables */
data seat[12];
int seatId, i,choice, num_Seat=0;
/* file pointers for marker,id and name respectively */
FILE *fpM, *fpID, *fpName;
/* load data from data file */
fpM = fopen("markerData", "rt");
fpID = fopen("idData","rt");
fpName = fopen("nameData","rt");
if ((fpM == NULL) || (fpID == NULL) || (fpName == NULL))
{printf("Error in loading data.\n");
return 0;}
for (i=0;i<12;i++)
{
seat[i].id = fgetc(fpID);
seat[i].marker = fgetc(fpM);
/* LINE A */
fscanf(fpName,"%s",seat[i].name);
}
fclose(fpM);
fclose(fpID);
fclose(fpName);
.............
/*
the main() receives inputs from user and managed to store them successfully in the array structure seat[12]. Then, the program quits and saves the data by calling quit().
*/
}
void quit(data seat[12])
{
int i;
FILE *fpM, *fpID, *fpName;
fpM = fopen("markerData", "wt");
fpID = fopen("idData","wt");
fpName = fopen("nameData","wt");
printf("Quiting....\n");
if ((fpM == NULL) || (fpID == NULL) || (fpName == NULL))
{printf("Error in saving data.\n");
return ;}
/* saving data */
for (i=0;i<12;i++)
{
fprintf(fpM,"%c",seat[i].marker);
fprintf(fpID,"%c",i+1);
/* LINE B */
fprintf(fpName,"%s",seat[i].name);
}
fclose(fpM);
fclose(fpID);
fclose(fpName);
}
My program cannot retrieve the datas from seat[i].name properly.
Strange characters are stored inside seat[i].name instead of what i intend.
Code:
However, if i changed the
line a:
fscanf(fpName,"%s",seat[i].name);
to
fscanf(fpName,"%s\n",seat[i].name);
AND
line b:
fprintf(fpName,"%s",seat[i].name);
to
fprintf(fpName,"%s\n",seat[i].name);
My program will be able to retrieve the datas out properly.
Can someone tell me why is it necessary to add the newline character? As i write each string into the file *fpName using fprintf(), is the NULL character added? Somehow i think my fscanf() doesnt recognise any NULL character during the loading at line a. That's why i couldnt retrieve the names out.