如何将文件中的网格读入 C 中的二维数组?
How to read a grid from a file into 2 dimensional array in C?
我尝试将文件中的网格读入二维数组。程序编译没有任何错误。这是代码:
#include <stdio.h>
#include <stdlib.h>
FILE* openFile(FILE* file, char* name, char* mode) {
file = NULL;
file = fopen(name, mode);
if(file == NULL) {
printf("Could not open a file!\n");
exit(1);
} else {
printf("File was opened/created successfully!\n\n");
}
return file;
}
int main() {
FILE* file;
file = openFile(file, "a.txt", "r");
char c;
int x, row, column;
x = row = column = 0;
int array[2][2];
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
array[i][j] = 0;
}
}
while(!feof(file) && (c = fgetc(file))) {
if(c == '\n') {
row++;
}
if(c != '\n' && c!= '\r') {
x = atoi(&c);
if(array[row][column] == 0) {
array[row][column] = x;
printf("array[%d][%d] = %d\n", row, column, array[row][column]);
printf("row = %d\n", row);
printf("column = %d\n\n", column);
column++;
}
}
}
for(int i = 0; i < row; i++) {
for(int j = 0; j < column; j++) {
printf("array[%d][%d] = %d\n", i, j, array[i][j]);
}
printf("\n");
}
fclose(file);
return 0;
}
txt 文件:
02
46
程序输出:
File was opened/created successfully!
array[0][0] = 0
row = 0
column = 0
array[0][1] = 2
row = 0
column = 1
array[0][0] = 0
array[0][1] = 2
似乎它只读取了第一行,然后是 feof() returns 它已经到了结尾。我访问了几个网站试图了解问题所在。
谁能解释一下我在哪里犯了错误并给出正确的解决方案?
您没有在更改行时重置列号。文件中的第二行保存在数组 [1][2] 和数组 [1][3] 中,但您不显示它。
while(!feof(file) && (c = fgetc(file))) {
if(c == '\n') {
row++;
column = 0;
}
这将正常工作。
我尝试将文件中的网格读入二维数组。程序编译没有任何错误。这是代码:
#include <stdio.h>
#include <stdlib.h>
FILE* openFile(FILE* file, char* name, char* mode) {
file = NULL;
file = fopen(name, mode);
if(file == NULL) {
printf("Could not open a file!\n");
exit(1);
} else {
printf("File was opened/created successfully!\n\n");
}
return file;
}
int main() {
FILE* file;
file = openFile(file, "a.txt", "r");
char c;
int x, row, column;
x = row = column = 0;
int array[2][2];
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
array[i][j] = 0;
}
}
while(!feof(file) && (c = fgetc(file))) {
if(c == '\n') {
row++;
}
if(c != '\n' && c!= '\r') {
x = atoi(&c);
if(array[row][column] == 0) {
array[row][column] = x;
printf("array[%d][%d] = %d\n", row, column, array[row][column]);
printf("row = %d\n", row);
printf("column = %d\n\n", column);
column++;
}
}
}
for(int i = 0; i < row; i++) {
for(int j = 0; j < column; j++) {
printf("array[%d][%d] = %d\n", i, j, array[i][j]);
}
printf("\n");
}
fclose(file);
return 0;
}
txt 文件:
02
46
程序输出:
File was opened/created successfully!
array[0][0] = 0
row = 0
column = 0
array[0][1] = 2
row = 0
column = 1
array[0][0] = 0
array[0][1] = 2
似乎它只读取了第一行,然后是 feof() returns 它已经到了结尾。我访问了几个网站试图了解问题所在。
谁能解释一下我在哪里犯了错误并给出正确的解决方案?
您没有在更改行时重置列号。文件中的第二行保存在数组 [1][2] 和数组 [1][3] 中,但您不显示它。
while(!feof(file) && (c = fgetc(file))) {
if(c == '\n') {
row++;
column = 0;
}
这将正常工作。