简体   繁体   English

C-从文件读取行

[英]C - reading lines from file

I am trying to read line by line from a file and print out the line. 我正在尝试从文件中逐行读取并打印出该行。 But when I run the code, it starts printing out the lines starting in the middle. 但是,当我运行代码时,它将开始打印从中间开始的行。

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);

Any reason for it to start in the middle? 有什么理由让它从中间开始?

Edit: So and example of what I mean in the middle is that I have a list like this 编辑:所以中间的意思是我有一个像这样的列表

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

and when I get to the printf it only shows this 当我进入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: I made a change in the program to get rid of the \\n in printf Edit2:我对程序进行了更改,以消除printf中的\\ n

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

and this fixed the problem. 这解决了问题。 Is there any reason why the \\n caused this problem? \\ n是否有任何原因导致此问题?

Take a look to Why is “while ( !feof (file) )” always wrong? 看一看为什么“ while(!feof(file))”总是错误的?

fgets is enough: fgets就足够了:

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

Also, don't use magic numbers like 300 , change to 另外,请勿使用像300这样的幻数

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

it starts printing out the lines starting in the middle 它开始打印从中间开始的行

Notice that fgets includes the trailing newline '\\n' and you don't need to include it in the printf , do you mean this by "in the middle"? 请注意, fgets包含尾随换行符'\\n'而您无需在printf包括它,您是说“在中间”吗?

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

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