Read File Element wise
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 开发者_JAVA技巧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
Keep a line and column count. Change the inside of the while loop
line = 0;
column = 0;
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
// fputs ( line, stdout ); /* write the line */
<FOR EVERY VALUE IN LINE>
{
matrix[line][column] = <VALUE>;
column++;
if (column == 4) {
column = 0;
line++;
}
}
}
As for the <FOR EVERY VALUE IN LINE> strtok()
comes to mind -- or you could use the is*
functions declared in <ctype.h>
.
If you absolutely trust the input, sscanf()
is a good option too.
You can use the fscanf
function.
#include <stdio.h>
int main ()
{
FILE* file;
int array[4][4];
int y;
int x;
file = fopen("matrix.txt","r");
for(y = 0; y < 4; y++) {
for(x = 0; x < 4; x++) {
fscanf(file, "%d", &(array[x][y]));
}
fscanf(file, "\n");
}
fclose (file);
for(y = 0; y < 4; y++) {
for(x = 0; x < 4; x++) {
printf("%d ", array[x][y]);
}
printf("\n");
}
return 0;
}
Note: in production code you should check the return value of fopen
(it might be NULL
), and the return value of fscanf
(did it read the expected amount of elements?).
fscanf to the rescue:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
FILE* file = fopen("input.txt", "r");
if (!file)
perror("Can't open input");
int matrix[4][4] = {
{ 0, 0, 0, 0, },
{ 0, 0, 0, 0, },
{ 0, 0, 0, 0, },
{ 0, 0, 0, 0, },
};
int i;
for (i=0; i<4; i++)
{
int n = fscanf(file, "%i %i %i %i", &matrix[i][0],
&matrix[i][1],
&matrix[i][2],
&matrix[i][3]);
if (n != 4) {
if (errno != 0)
perror("scanf");
else
fprintf(stderr, "No matching characters\n");
}
}
for (i=0; i<4; i++)
printf("%i %i %i %i\n", matrix[i][0],
matrix[i][1],
matrix[i][2],
matrix[i][3]);
}
Of course you need to make the code more generic
精彩评论