C stdin 无限读取文件

标签 c stdin infinite

我有一个基本的 C 程序,需要从 stdin 读取输入。 首先,它使用

从输入文件中读取
./Program <input

然后循环读取,直到没有更多

while(scanf("%s",command)!=EOF){
    printf("%s\n",command);
}

之后,我需要再次从键盘读取数据,但它继续无限地从我的输入文件中读取最后一行,不让我使用键盘进行输入。

 while(1){

 scanf("%s",command);
 if(!strcasecmp(command,"exit"))
  exitProg();
 else if(!strcasecmp(command,"help"))
  helpMess();
 else
  printf("Command \"%s\" not recognized, use command \"help\" for a list.\n",command);
 }

最佳答案

阅读documentation for scanf ,具体是关于返回值的部分,摘录如下:

Return Value

On success, the function returns the number of items successfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read, EOF is returned.

您遇到的问题是,一旦文件用完数据,程序的标准输入不会恢复到控制终端,它停留在空文件的末尾。您的 scanf 调用默默失败,使 command 的内容保持不变。如果您希望能够同时读取两者,则需要找到另一种处理方法。

您的 shell 可能支持此功能。

关于C stdin 无限读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12306610/

相关文章:

c++ - 链接上 undefined symbol ___gxx_personality_v0

python - 在 os.dup2() 之后重定向标准输出/输入/错误

Python fermat 程序仅适用于低数字

R、STDIN 到 Rscript

python - 将 "Infinite" float 转换为整数

android - WebView 无限扩展 - 如何防止这种情况发生?

c - 指向数组的指针错误

c - 使用 C 的 Kruskal 算法

c - 尝试创建线程时 malloc 出错

python - 如何从 stdin 读取输入并强制执行编码?