简体   繁体   English

如何使用 fgets() 从 stdin 读取?

[英]How to read from stdin with fgets()?

My professor write a C code about fgets,feof with using stdin.我的教授写了一个 C 代码关于 fgets,feof 使用标准输入。 But I don't understand how it works.但我不明白它是如何工作的。

fgets(list, 100, stdin);

while (!feof(stdin))
{
    printf("feof!");
    
    fgets(list, 100, stdin);
}

when i write a 'hello', function while is working.当我写“你好”时,function 正在工作。 why feof(stdin) returns 0?为什么 feof(stdin) 返回 0?

I think first fgets read stdin buffer all of string(include '\0').我认为首先 fgets 读取标准输入缓冲区中的所有字符串(包括 '\0')。 therefore I think while shouldn't work because feof(stdin) returns 1 What am i wrong?因此我认为 while 不应该工作因为 feof(stdin) 返回 1 我错了什么?

Tip: always check the return value of input functions and most other I/O functions too.提示:始终检查输入函数和大多数其他 I/O 函数的返回值。

fgets(list, 100, stdin);  // Weak code

Yes, calling printf("feof;");是的,调用printf("feof;"); inside the loop is misleading as the end-of-file indicator for stdin is not set given the prior test condition while (!feof(stdin)) .循环内部具有误导性,因为在给定先前测试条件while (!feof(stdin))的情况下,未设置stdin的文件结束指示符。

How to read from stdin with fgets()?如何使用 fgets() 从 stdin 读取?

Do not use feof() for this task for primary detection不要将feof()用于此任务以进行初级检测

fgets() returns NULL when: fgets()在以下情况下返回NULL

  1. An end-of-file just occurred in the previous input operation.上一个输入操作刚刚发生了文件结束。

  2. An end-of-file had occurred in the some input operations even before that.甚至在此之前,一些输入操作已经发生了文件结束。

  3. An input error just occurred.刚刚发生输入错误。 Examples: file to read is an output stream or a parity error on some serial communication.示例:要读取的文件是 output stream 或某些串行通信的奇偶校验错误。

while (!feof(stdin)) only detects 1 & 2. while (!feof(stdin))仅检测 1 和 2。

Unless the return value of fgets(list, 100, stdin) is checked, using list may be a problem.除非检查fgets(list, 100, stdin)的返回值,否则使用list可能会有问题。

feof() is useful after an I/O function returned the possibility of the need. feof()在 I/O function 返回需要的可能性很有用。

Size to the object, avoid magic numbers大小为 object,避免幻数


Good usage:好的用法:

char list[100];
while (fgets(list, sizeof list, stdin)) {
  printf("%s", list):
}

if (feof(stdin)) {
  puts("End-of-file");
} else if (ferror(stdin)) {
  puts("Error");
} else {
  puts("Unexpected state");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM