我需要读取C中的文件,将其存储在数组中并打印其内容.出于某种原因,我一直看到我的输出中的八进制接近尾声.我在计算打开文件后计算了多少行和字符后动态创建数组.
输出:
Abies
abies
abietate
abietene
abietic
abietin
\320?_\377Abietineae --> umlaut? where did he come from?
y\300_\377abietineous
Run Code Online (Sandbox Code Playgroud)
码:
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;
}
Run Code Online (Sandbox Code Playgroud)
更改读取例程:
if (c == '\n'){
word[i][j] = 0x0;
i++; j=0;
continue;
}
Run Code Online (Sandbox Code Playgroud)
并在printf例程中添加"\n".
for (i = 0; i < max_line; i++){
printf("%s\n", word[i]);
}
Run Code Online (Sandbox Code Playgroud)
C字符串是零终止的,而不是"\n" - 终止,所以当你printf()编辑它们时,printf()
不知道在哪里停止打印.
你没有终止你的字符串.您需要在\0
每行的最后一个字符后添加null-terminator : .
在第一个循环中,为最长的行确定足够的空间,包括换行符.
如果要在输入数组中保留换行符,只需添加1 max_char_per_line
,并在第二个循环中完成每一行后,在换行符后添加null终止符.
如果您不需要输入数组中的换行符,而只需将该空格用于null终止符.