I am working on a game program that requires me to save a 2D array into a file, and then if the user wants to go back to that game then can load it back up and continue it. But I am having a problem with getting the array to save into a txt file. And for the load function, it is not being able to load anything. The user is supposed to select the load option and it should be able to call the txt file with the array and then allows them to continue playing the game.
This is my save function
void save(char *filename)
{
FILE *fp = fopen(filename, "wb");
fwrite(&size, sizeof(size), 1 , fp);
fwrite(board, sizeof(int), size, fp);
if(fp == NULL)
return;
fclose(fp);
}
This is my load function
void load(char *filename)
{
FILE *fp = fopen(filename, "rb");
fread(&size, sizeof(size), 1 , fp);
fread(board, sizeof(int), size, fp);
if(fp == NULL)
return;
fclose(fp);
}
Later in the code, I use a menu to call these functions. Any help would be very appreciated!
CodePudding user response:
board
is not a 2D array, it's an array of pointers to rows. You need to loop over it, writing and reading each row separately.
Since the size of the board being loaded may be different from the board currently in memory, you need to free the old board and re-allocate the new one when loading.
void save(char *filename)
{
FILE *fp = fopen(filename, "wb");
if (!fp) {
perror("Can't open save file");
return;
}
fwrite(&size, sizeof(size), 1 , fp);
for (int i = 0; i < size; i ) {
fwrite(board[i], sizeof(*board[i]), size, fp);
}
fclose(fp);
}
void load(char *filename)
{
FILE *fp = fopen(filename, "r");
if (!fp) {
perror("Can't open save file");
return;
}
if (board) {
for (int i = 0; i < size; i ) {
free(board[i]);
}
free(board);
}
fread(&size, sizeof(size), 1 , fp);
board = malloc(size * sizeof(*board));
for (int i = 0; i < size; i ) {
board[i] = malloc(size * sizeof(*board[i]));
fread(board[i], sizeof(*board[i]), size, fp);
}
fclose(fp);
}
CodePudding user response:
First of all, write RB
while loading. Second, don't forget to close all of the files after entering the FILE
command.
Additionally, I have advice for you: Always check if *fp
is equal to NULL
; it's great for debugging and can have huge impact on your code. You can also write a function for multiple checking while using file in your program.