明智地阅读文件元素(Read File Element wise)
我想读取包含4X4矩阵数据的文本文件,每个元素用空格分隔,它被分成4行代表矩阵。 它是以下面的形式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16现在我遇到了代码
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;它读取文件,但我想知道如何读取元素,以便我可以将它们存储在2D数组中
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 16now 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救援:
#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]); }当然,您需要使代码更通用
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
更多推荐
发布评论