I have an array, which holds 6 words and a secret word
char boardInputs[7][6];
I need to autosave to binary file this array every time when user entered the word. After restarting the program, I need to read the saved array of words from the binary file and install it into the input data array of the board
void readArray(int rows, int cols, char array[rows][cols]) {
FILE *data;
data = fopen("autosave.bin", "rb");
fread(array, sizeof(char[rows][cols]), 1, data);
}
void autoSave() {
int result = EXIT_SUCCESS;
char file_name[] = "autosave.bin";
FILE *fp = fopen(file_name, "wb");
if (fp == NULL) {
result = EXIT_FAILURE;
fprintf(stderr, "fopen() failed for '%s'\n", file_name);
} else {
size_t element_size = sizeof *boardInputs;
size_t elements_to_write = sizeof boardInputs;
size_t elements_written = fwrite(boardInputs, element_size, elements_to_write, fp);
if (elements_written != elements_to_write) {
result = EXIT_FAILURE;
fprintf(stderr, "fwrite() failed: wrote only %zu out of %zu elements.\n",
elements_written, elements_to_write);
}
fclose(fp);
}
}
int main() {
int cols = 7;
int rows = 6;
char (*myArray)[cols] = allocArray(rows, cols);
readArray(rows, cols, myArray);
strcpy(boardInputs, myArray);
free(myArray);
}
I created this code, but the words from the binary file are set incorrectly. How to fix it?
readArray(). Please update question to make it a minimal reproducible example. It's close but missing headers and example data (or rewrite it so it first saves some hard-coded data then reads it back) to demonstrate what the issue is.