Zatial je tu mnoho filozofickej diskusie, ale malo kodu, tak postnem ja - ako som uz vyssie spomenul, da sa to vyriesit so standardnymi C funkciami fgets() a strtok() napr. takto:
matrix.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ROWS 100
#define MAX_COLS 100
#define MAX_LINE_LENGTH 256
int main()
{
FILE *fp;
char matrix_line[MAX_LINE_LENGTH];
char *matrix_element;
int i, j, max_i, max_j;
int num_element;
int matrix[MAX_ROWS][MAX_COLS];
fp = fopen("matrix.dat","r");
printf("Reading data from the file into the matrix:\n");
i = 0;
while (fgets(matrix_line, MAX_LINE_LENGTH, fp) != NULL) {
// split line into matrix elements
matrix_element = strtok(matrix_line, ",;\t ");
j = 0;
while(matrix_element != NULL) {
// populate matrix
matrix[i][j] = atoi(matrix_element);
j++;
matrix_element = strtok(NULL, ",;\t ");
}
i++;
}
max_i = i;
max_j = j;
fclose(fp);
printf("..DONE.\n\n");
// now print the matrix
printf("The matrix is:\n");
for (i = 0; i < max_i; i++) {
for (j = 0; j < max_j; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Nacita zo suboru matica.dat takuto
1 2 3 4
5 6 7 8
alebo aj takuto maticu kde su prvky oddelene roznymi separatormi.
1; 2, 3 4
5 6; 7 8
Output:
$ gcc matrix.c -o matrix
$ matrix
Reading data from the file into the matrix:
..DONE.
The matrix is:
1 2 3 4
5 6 7 8