我尝试从文件中将网格读取到二维数组中。程序编译时没有任何错误。这是代码:
#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!nn");
}
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] = %dn", row, column, array[row][column]);
printf("row = %dn", row);
printf("column = %dnn", column);
column++;
}
}
}
for(int i = 0; i < row; i++) {
for(int j = 0; j < column; j++) {
printf("array[%d][%d] = %dn", 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()返回它已经到达末尾。我访问了一些网站,试图了解哪里出了问题。
有人能解释一下我犯的错误在哪里,并给出正确的解决方案吗?
更改行时不会重新设置列编号。文件中的第二行保存在数组[1][2]和数组[1][3]中,但您不显示它。
while(!feof(file) && (c = fgetc(file))) {
if(c == 'n') {
row++;
column = 0;
}
这将正常工作。