i want to read text file containing the data of 4X4 matrix each element is separated by a space and it is divided into 4 rows which represent the matrix. it is in Following form
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
now i came across the code that
static const char filename[] = "file.txt";
FILE *file = fopen ( filename, "r" );
if ( file != NULL )
{
char line [ 128 ]; /* or other suitable maximum line size */
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
fputs ( line, stdout ); /* write the line */
}
fclose ( file );
}
else
{
perror ( filename ); /* why didn't the file open? */
}
return 0;
which reads the file but i want to know that how to read them element wise so that i can store them in 2D array
fscanf to the rescue:
Of course you need to make the code more generic