我需要从 C 中读取一个文件,将其存储在一个数组中并打印其内容。出于某种原因,我在接近尾声的输出中不断看到八进制。在打开文件后计算其中有多少行和字符后,我正在动态创建数组。
输出:
Abies
abies
abietate
abietene
abietic
abietin
\320ѿ_\377Abietineae --> umlaut? where did he come from?
y\300_\377abietineous
代码:
int main(int argc, char ** argv) {
char c = '\0';
FILE * file;
int i = 0, j = 0, max_line = 0, max_char_per_line = 0;
/* get array limits */
file = fopen(argv[1], "r");
while ((c = fgetc(file)) != EOF){
if (c == '\n'){
max_line++; j++;
if (j > max_char_per_line){
max_char_per_line = j;
}
j = 0;
continue;
}
j++;
}
rewind(file);
/* declare array dynamically based on max line and max char */
char word[max_line][max_char_per_line];
/*read in file*/
j = 0; c = '\0';
while ((c = fgetc(file)) != EOF){
if (c == '\n'){
word[i][j] = '\0';
i++; j=0;
continue;
}
word[i][j] = c;
j++;
}
word[i][j] = '\0';
fclose(file);
for (i = 0; i < max_line; i++){
printf("%s\n", word[i]);
}
return 0;
}