明智地阅读文件元素(Read File Element wise)

编程入门 行业动态 更新时间:2024-10-26 14:28:02
明智地阅读文件元素(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 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救援:

#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

更多推荐

本文发布于:2023-04-27 15:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327216.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:明智   元素   文件   Read   Element

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!