【发布时间】: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