问题
Bit of background, I'm writing a program that plays the game "boxes" it runs in linux command line and is written in C. There's a prompt that waits for user input and then is read with fgets() and interpretted etc.
As part of the task specification I have to return a specific error if I reach "End of file while waiting for user input". I understand that fgets() returns null when it reaches EOF... but say I have
fgets(input,max_buffer,stdin);
in a prompt loop if the user exits prematurely say with CTRL+C or CTRL+D does this mean that input == NULL?
Can I even detect when a user does this with fgets?
Just trying to get my head around this, thanks in advance for any help.
(OS: UNIX) (Compiler: gcc - c90)
回答1:
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
}
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/32040526/detecting-eof-with-fgets-where-filesteam-is-stdin