为什么我在使用 fgets 时必须输入 3 次 EOF? [英] Why do i have to input EOF 3 times when using fgets?
问题描述
所以基本上我想将我写入标准输入(包括换行符)的所有内容复制到字符串以用于哈希目的.我设法做到了这一点,并编写了一些小代码来表示我的问题.
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("
%s
",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:
- 刷新输入(即将已经输入的字符从终端发送到程序 - 默认情况下这不会发生,因为终端使用行缓冲)
- 设置文件结束条件
- 再次设置文件结束条件
在你的程序里面对应:
- 什么也没发生:即使接收到
a
,fgets
也会一直读取直到文件结束或换行 fgets
由于文件结束而完成.但是它不会返回 NULL 因为字符被读取,"a"
是特定的.fgets
因为文件结束而完成,并返回NULL
因为没有读取字符.
- Nothing happens: even though
a
is received,fgets
keeps reading until end-of-file or newline fgets
completes because of end-of file. However it does not return NULL because characters were read,"a"
to be specific.fgets
completes because of end-of-file, and returnsNULL
because there were no characters read.
这篇关于为什么我在使用 fgets 时必须输入 3 次 EOF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!