使用fgets()检测EOF,其中fileteam是stdin [英] Detecting EOF with fgets() where filesteam is stdin

查看:188
本文介绍了使用fgets()检测EOF,其中fileteam是stdin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有点背景,我正在写一个程序,玩在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


从流中读取字符并将它们作为C字符串存储到str中,直到已读取(num-1)个字符或

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.

换行符使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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆