问题描述
有点背景,我正在写一个程序,玩在Linux命令行中运行并用C编写的盒子游戏。有一个提示,等待用户输入,然后用fgets()读取并解释
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.
作为任务说明的一部分,如果到达等待用户输入时文件结束,我必须返回一个特定错误。我知道fgets()到达EOF时会返回null ...但是说我有
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);
在提示循环中,如果用户过早退出,请说用CTRL + C或CTRL + D表示输入== NULL吗?
in a prompt loop if the user exits prematurely say with CTRL+C or CTRL+D does this mean that input == NULL?
我什至可以检测到用户何时使用fgets执行此操作?
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.
(操作系统:UNIX)
(编译器:gcc-c90)
(OS: UNIX)(Compiler: gcc - c90)
推荐答案
从, fgets
:
换行符使fgets停止读取,但该函数将其视为有效字符并包含在字符串中复制到str。
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.
在复制到str的字符之后会自动附加一个终止的空字符。
A terminating null character is automatically appended after the characters copied to str.
fgets
将在用户输入CTRL-D(文件末尾)或时返回,当 \n
(换行符)。 CTRL-C默认情况下会 完全终止程序。
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.
如果您想捕获CTRL-C并正常退出,则可以:
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
}
这篇关于使用fgets()检测EOF,其中fileteam是stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!