为什么在使用fgets时必须输入EOF 3次? [英] Why do i have to input EOF 3 times when using fgets?

查看:190
本文介绍了为什么在使用fgets时必须输入EOF 3次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,基本上我想将我写到stdin的所有内容(包括换行符)复制到字符串中以用于哈希。我设法做到了这一点,并编写了一些小代码来表示我的问题。

So basically I want to copy everything i write to stdin (including newline char) to string for hash purposes. I managed to accomplish that and made small code to represent my problem.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUFFERSIZE 10000

int main()
{
char *myStr = calloc(1,1);
char buffer[BUFFERSIZE];

while( fgets(buffer, BUFFERSIZE , stdin) != NULL ){
  myStr = realloc(myStr, strlen(myStr)+1+strlen(buffer) );
  strcat( myStr, buffer );
}
printf("\n%s\n",myStr);

}

当我输入一些文本然后按ENTER之后,一切正常我叫EOF。

everything works when I enter some text then press ENTER and after I call EOF.

但是当我启动程序时输入 a,然后我尝试调用EOF(使用 Ctrl Z + (Windows cmd提示符), Ctrl D (Linux))我必须执行三遍,程序才能真正打破循环。我期望最多2次。

But when I start program enter "a" then I try to call EOF (using Ctrl Z + (Windows cmd prompt), Ctrl D (Linux)) I have to do it three times for program to actually break the loop. I was expecting maximum of 2 times.

有人可以解释如何使用EOF,stdin和fgets吗?还是我应该使用其他东西(例如,getline)?很抱歉,如果我不清楚我的问题,请问任何您需要的东西。

Can someone explain how using EOF, stdin and fgets works? Or should I use something else (for example getline)? I am sorry if I am not clear about my problem, just ask anything you need.

谢谢。

推荐答案

首先,^ Z或^ D是控制字符,对于您正在使用的终端表示某些含义,而有时则表示对终端发出结束信号

First of all, ^Z or ^D are control characters that mean something to the terminal you are using, and sometimes that means for the terminal to signal end-of-file condition.

无论如何,在输入文本之后,终端会处理您的三个按键以执行以下操作:

Anyway, your three keypresses are processed by the terminal to take the following actions, after entering text:


  1. 刷新输入(例如,将已输入的字符从终端发送到程序中-默认情况下,由于终端使用行缓冲,因此不会发生这种情况)

  2. 设置文件结束条件

  3. 再次设置文件结束条件

在与以下内容相对应的程序内部:

Inside your program that corresponds to:


  1. 没有任何反应:即使 a 已收到, fgets 一直读取直到文件结束或换行符

  2. fgets c由于文件末尾而无法完成。但是,它不会返回NULL,因为已读取字符, a 是具体的。

  3. fgets 由于文件结尾而完成,并由于未读取任何字符而返回 NULL

  1. Nothing happens: even though a is received, fgets keeps reading until end-of-file or newline
  2. fgets completes because of end-of file. However it does not return NULL because characters were read, "a" to be specific.
  3. fgets completes because of end-of-file, and returns NULL because there were no characters read.

这篇关于为什么在使用fgets时必须输入EOF 3次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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