I’m learning C and I decided to make a text game as my learning project. So I’m trying this primitive “parser” that reads a text file into a 2D array, but there’s a problem: this map doesn’t use 1 character-wide cells, it uses 2 character-wide cells. For instance, the player is represented with a **, a door is represented like ## and so on.
That means, I need to read 2 characters of the text file and then assign it to the respective cell in the map.
Well, I made a test file that contains
aabbccddee
ffgghhiijj
kkllmmnnoo
ppqqrrsstt
uuvvwwxxyy
And I tried to read it with
#include <stdio.h>
#define ROWS 5
#define COLS 5
int main() {
FILE *mapfile = fopen("durr", "r");
char charbuffer[3], row, col, *map[ROWS][COLS];
/* Initializing array */
for (row = 0; row < ROWS; row++) {
for (col = 0; col < COLS; col++) {
map[row][col] = " ";
}
}
/* Reading file into array */
for (row = 0; row < ROWS; row++) {
for (col = 0; col < COLS; col++) {
map[row][col] = fgets(charbuffer, 3, mapfile);
}
}
/* Printing array */
for (row = 0; row < ROWS; row++) {
for (col = 0; col < COLS; col++) {
printf("%s", map[row][col]);
}
printf("\n");
}
fclose(mapfile);
return 0;
}
But when I execute it, I get this
uuuuuuuuuu
uuuuuuuuuu
uuuuuuuuuu
uuuuuuuuuu
uuuuuuuuuu
I think it has something to do with the fact that fgets return a pointer, but I’m not sure. I tried doing it with fgetc but it looks messy and I dropped it after reading about gets.
You should have strdup’ed the contents read from the file. Replace the file reading block with this:
and don’t forget to put this at the beginning of your code too: