TransWikia.com

Recognizing EOF vs newline in getline in C

Stack Overflow Asked by Jan Dunder on January 26, 2021

is there any way how to recognize if getline was ended because of newline or because of EOF?

So, I would like to distinguish:

1.
alfa n beta n gama n EOF

2.
alfa n beta n gama 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. I am using while cycle to read the lines.

I can’t edit incoming data.

There is probably possibility to solve this by using getchar. However it makes reading lines more complicated :-/

Thank you so much

3 Answers

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

Answered by Jan Dunder on January 26, 2021

is there any way how to recognize if getline was ended because of newline or because of EOF?

If the line input stopped due to end-of-file, feof() returns 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.

Answered by chux - Reinstate Monica on January 26, 2021

Like fgets(), getline() includes the trailing newline in the string. So just check the last character after a successful call to see if it's a 'n'. If it's something else, you have the last line of a file without a trailing newline.

Answered by Shawn on January 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP