I try to read a grid from a file into a 2 dimensional array. The program compiles without any errors. Here is the code:
#include <stdio.h>
#include <stdlib.h>
FILE* openFile(FILE* file, char* name, char* mode) {
file = NULL;
file = fopen(name, mode);
if(file == NULL) {
printf("Could not open a file!\n");
exit(1);
} else {
printf("File was opened/created successfully!\n\n");
}
return file;
}
int main() {
FILE* file;
file = openFile(file, "a.txt", "r");
char c;
int x, row, column;
x = row = column = 0;
int array[2][2];
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
array[i][j] = 0;
}
}
while(!feof(file) && (c = fgetc(file))) {
if(c == '\n') {
row++;
}
if(c != '\n' && c!= '\r') {
x = atoi(&c);
if(array[row][column] == 0) {
array[row][column] = x;
printf("array[%d][%d] = %d\n", row, column, array[row][column]);
printf("row = %d\n", row);
printf("column = %d\n\n", column);
column++;
}
}
}
for(int i = 0; i < row; i++) {
for(int j = 0; j < column; j++) {
printf("array[%d][%d] = %d\n", i, j, array[i][j]);
}
printf("\n");
}
fclose(file);
return 0;
}
txt file:
02
46
Output of the program:
File was opened/created successfully!
array[0][0] = 0
row = 0
column = 0
array[0][1] = 2
row = 0
column = 1
array[0][0] = 0
array[0][1] = 2
Seems like it reads only the first line and then feof() returns that it has reached the end. I have visited a few websites trying to understand what is wrong.
Could anyone explain where is the mistake i made and show the correct solution?