繁体   English   中英

C-从文件读取行

[英]C - reading lines from file

我正在尝试从文件中逐行读取并打印出该行。 但是,当我运行代码时,它将开始打印从中间开始的行。

char temp[300];

if (input == NULL) {
    printf("Can't open input file.\n");
    exit(-1);
}

while (!feof(input)) {
    fgets(temp, 300, input);
    printf("%s \n", temp);
}
fclose(input);

有什么理由让它从中间开始?

编辑:所以中间的意思是我有一个像这样的列表

7,12 Angry Men,1957
95,2001: A Space Odyssey,1968
211,8 and a Half,1963
190,A Beautiful Mind,2001
68,A Clockwork Orange,1971
223,A Fistful of Dollars,1964
108,A Separation,2011
233,A Streetcar Named Desire,1951
40,Alien,1979
58,Aliens,1986
96,All About Eve,1950
224,All Quiet on the Western Front,1930
250,All the President's Men,1976
91,Amadeus,1984
69,Amelie,2001
54,American Beauty,1999
33,American History X,1998
189,Amores Perros,2000

当我进入printf时,它只显示

58,Aliens,1986
96,All About Eve,1950
224,All Quiet on the Western Front,1930
250,All the President's Men,1976
91,Amadeus,1984
69,Amelie,2001
54,American Beauty,1999
33,American History X,1998
189,Amores Perros,2000

Edit2:我对程序进行了更改,以消除printf中的\\ n

while (fgets(temp, sizeof(temp), input) != NULL) {
        printf("%s", temp);
    }

这解决了问题。 \\ n是否有任何原因导致此问题?

看一看为什么“ while(!feof(file))”总是错误的?

fgets就足够了:

while (fgets(temp, 300, input) != NULL) {
    printf("%s \n", temp);
}

另外,请勿使用像300这样的幻数

while (fgets(temp, sizeof temp, input) != NULL) {
    printf("%s \n", temp);
}

它开始打印从中间开始的行

请注意, fgets包含尾随换行符'\\n'而您无需在printf包括它,您是说“在中间”吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM