简体   繁体   中英

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?

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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