我需要從C中讀取文件,將其存儲在數組中並打印其內容。出於某種原因,我在結尾處看到八進制輸出。我在計算打開文件後計算其中有多少行和字符後,動態創建數組。將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;
}
代碼更新爲空間和製表符。 –