简体   繁体   English

在 C 中的 getline 中识别 EOF 与换行符

[英]Recognizing EOF vs newline in getline in C

is there any way how to recognize if getline was ended because of newline or because of EOF?有什么方法可以识别 getline 是因为换行还是因为 EOF 而结束?

So, I would like to distinguish:所以,我想区分:

1. alfa \\n beta \\n gama \\n EOF 1.阿尔法\\n测试版\\n伽马\\nEOF

2. alfa \\n beta \\n gama EOF 2.阿尔法\\n测试版\\n伽马EOF

In the second case I don't want to read gama as a new string and I want to say, that the reading of last string was not successful.在第二种情况下,我不想将 gama 作为新字符串读取,我想说的是,最后一个字符串的读取不成功。 I am using while cycle to read the lines.我正在使用 while 循环来阅读这些行。

I can't edit incoming data.我无法编辑传入的数据。

There is probably possibility to solve this by using getchar.可能有可能通过使用 getchar 来解决这个问题。 However it makes reading lines more complicated :-/然而,它使阅读线条更加复杂:-/

Thank you so much非常感谢

Like fgets() , getline() includes the trailing newline in the string.fgets()getline()包括字符串中的尾随换行符。 So just check the last character after a successful call to see if it's a '\\n' .因此,只需在成功调用后检查最后一个字符,看看它是否是'\\n' If it's something else, you have the last line of a file without a trailing newline.如果是其他内容,则文件的最后一行没有尾随换行符。

is there any way how to recognize if getline was ended because of newline or because of EOF?有什么方法可以识别 getline 是因为换行还是因为 EOF 而结束?

If the line input stopped due to end-of-file, feof() returns true.如果行输入由于文件结束而停止,则feof()返回 true。

ssize_t nread = getline(&line, &len, stream);
if (feof(stream)) {
  puts("Input ended due to end-of-file");
}
if (nread > 0 && line[nread-1] == '\n') {
  puts("Input ended due to end-of-line");
}

It is possible for both to be false: input error or allocation failure.两者都可能为假:输入错误或分配失败。


Concerning fgets() , additional issues occur when the buffer is full or a null character was read.关于fgets() ,当缓冲区已满或读取空字符时会出现其他问题。

Thank you for your tips.谢谢你的提示。

Finally I used easier way how to do it.最后我使用了更简单的方法来做到这一点。

characters = getline(&line, &len, stream);

if (characters==-1) {puts("Input ended by EOF after \\n");}

if (feof(stdin)) {puts("Input ended by just EOF");}

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

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