Code:
void printtable(struct country *array)
{
for (int i = 0; array.name != NULL; i++) { //Moving through the array of structs until NULL character.
printf("%s %d %d %d\n", array.name, array.medals.gold, array.medals.silver,
array.medals.bronze);
}
}
void save_table(struct country *p, char *name)
{
char *filename = malloc(sizeof(name));
strcpy(filename, name);
FILE *file;
file = fopen(filename, "w");
fwrite(&p, sizeof(struct country), 1, file);
fclose(file);
}
void load_table(struct country *p, char *name)
{
char *filename = malloc(sizeof(name));
strcpy(filename, name);
FILE *file;
file = fopen(filename, "r");
if (file != NULL) {
while (1) {
if (feof(file)) {
printf("File Loaded Successfully!\n");
break;
} else {
fscanf(file, "%s %d %d %d", p->name, &(p->medals.gold),
&(p->medals.silver), &(p->medals.bronze));
}
}
} else {
printf
("File failed to open due to either wrong name input, or nonexisting file.\n");
return;
}
fclose(file);
}
int main()
{
struct country *array = malloc(sizeof(struct country));
array[0].name = NULL; //Initialize array
char input[80]; //User input line
char name[20]; //String for handling the name input
int number = 0; //Keeping track of the number of countries
printf("Enter country and medals\n");
printf("\n");
while (1) { //Loops forever until "break" command
fgets(input, sizeof(input), stdin); //Gets input from user
if (input[0] == 'A') {
sscanf(input, "%*c %s", name); //Reads input, ignoring the first "command" character
array = add_country(array, name);
if (array == NULL) {
printf("\nCreating country failed");
} else {
number++; //Increases the number of countries
}
} else if (input[0] == 'M') {
int g, s, b; // Gold, Silver and Bronze medal count;
sscanf(input, "%*c %s %d %d %d", name, &g, &s, &b); //Reads input, ignoring the first "command" character
update_medals(array, name, number, g, s, b);
} else if (input[0] == 'L') {
printtable(array);
} else if (input[0] == 'W') {
sscanf(input, "%*c %s", name); //Reads input, ignoring the first "command" character
save_table(array, name);
} else if (input[0] == 'O') {
sscanf(input, "%*c %s", name); //Reads input, ignoring the first "command" character
load_table(array, name);
} else if (input[0] == 'Q') {
free(array);
printf("Exiting program.\n");
break;
}
}
return 0;
}
I'm trying to read my array structs to a file with the command "W filename" and then load the file (write the file to a struct) with the command "O filename". A problem occurs when I try to print the table after I've loaded the file. The first character prints something entirely random, however the rest of the content are right.