Detecting EOF with fgets() where filesteam is stdin

不想你离开。 提交于 2019-12-06 01:34:08

From here, fgets:

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.

A terminating null character is automatically appended after the characters copied to str.

So, fgets will return when the user inputs CTRL-D (end-of-file) or, when a \n (newline) is encountered. CTRL-C will by default terminate your program entirely.

If you'd like to catch CTRL-C, and exit gracefully, you could:

#include <signal.h>

void intHandler(int dummy) {
    //graceful CTRL-C exit code.
}

int main(void) {
    signal(SIGINT, intHandler);
    //your code
}

The documentation (C99 §7.19.7.2):

The fgets function returns s if successful. If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned. If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned.

So if an end-of-file occurs, but characters have been read, fgets will not return NULL. If EOF happens before any input was read, it will return NULL.

You can differentiate between EOF and a read error with the feof and ferror functions.

When the end-user exits permanently with Ctrl+C, your program loses control right away, meaning that you do not get any further input from fgets, not even a NULL.

Ctrl+D, on the other hand, closes the input stream without closing your program, so you would get a NULL result from the fgets call.

You can set your program up to handle Ctrl+C by handling a signal, but such handling would happen outside the input loop.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!