I have file called input1.txt,which is a matrix of numbers and some letters.I am trying to read and store it in a 2D array so that each charter will be 1 cell. Here is my text file:
1111S11110
0000010001
110100010d
t001111110
0100000001
0111111101
1111111101
00000D01T1
0111110001
0000E01110
And here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function for finding the array length
int numOfLines(FILE *const mazeFile){
int c, count;
count = 0;
for( ;; ){
c = fgetc(mazeFile);
if( c == EOF || c == '\n' )
break;
++count;
}
return count;
}
// Main Function
int main( int argc, char **argv )
{
// Opening the Matrix File
FILE *mazeFile;
mazeFile = fopen( "input1.txt", "r" );
if( mazeFile == NULL )
return 1;
int matrixSize = numOfLines( mazeFile );
// Reading text file into 2D array
int i,j;
char mazeArray [matrixSize][matrixSize];
for(i=0;i<matrixSize;i++){
for(j=0;j<matrixSize;j++){
fscanf(mazeFile,"%c", &mazeArray[i][j]);
}
}
for(i=0;i<matrixSize;i++){
for(j=0;j<matrixSize;j++){
printf("%c",mazeArray[i][j]);
}
}
fclose( mazeFile );
return 0;
}
However my console output is like that when i print them:
0000010001
110100010d
t001111110
0100000001
0111111101
1111111101
00000D01T1
0111110001
0000E01110@
Seems it does not read the 1st line,However in terms of indexes i think it is ok.I am new to C.Could anyone please help.Thanks in advance.
numOfLinesis a misnomer, it counts the number of characters in the first line. And therefore, reads them! Why do you think if you continue reading, you would restart from the beginning? magic? Tryrewind().numOfLines()function reads the file to the end. If you want to re-read it, you need to seek back to the beginning (which is possible for regular files, but not for some other possible kinds of streams).