【问题标题】:fgets() goes into infinite loop reading from stdinfgets() 进入从标准输入读取的无限循环
【发布时间】:2014-01-07 13:46:18
【问题描述】:

我编写了以下代码,但它陷入了无限循环。有人可以帮我解决这个问题吗?

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

void main()
{
    FILE *fp;
    char s[10];


    fp=fopen("text1.txt", "w");

    if(fp==NULL)
    {
        printf("Error opening file\n");
        exit(1);
    }

    while(fgets(s, sizeof(s), stdin)!=NULL)//Reads until the NULL character.
        fputs(s, fp);//Write to the file pointed by fp..


    fclose(fp);
    getch();
}

【问题讨论】:

  • 如何终止输入?即,您如何告诉您的程序输入已到达“文件末尾”?
  • 错误消息很重要:perror( "text1.txt" )。更好的是:fp = fopen( argv[1], "w"); if ( fp == NULL ) { perror( argv[1] ); exit EXIT_FAILURE; }
  • 最后的 getch 毫无意义,因为 while 循环将消耗所有输入。
  • 在 ubuntu 中,上面的代码在 ctrl-D 前面加上 newline 时可以正常工作。

标签: c stdin infinite-loop fgets


【解决方案1】:

该程序将按预期运行,直到输入信号“文件结束”。

如果您没有使用输入重定向(例如,以myprogram &lt; somefile.txt 运行它)而是使用控制台(键盘)作为输入设备运行,您必须手动发出文件结束信号以导致循环结束。

在 Linux 中,这是通过按 Ctrl+D 来完成的,在 Windows 中是 Ctrl+Z。

【讨论】:

    【解决方案2】:

    如果您正在输入输入,请使用 ctrl+z 来终止输入。我在 linux 上尝试了代码,它工作正常。ctrl kbd>+z 表示windows上的EOF。

    如果您没有输入输入并使用重定向,则代码可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-07
      • 2013-03-17
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多