C语言如何从键盘输入一些字符,逐个把它们存入磁盘文件test中去,直到输入一个#为止?

2024-11-19 11:46:20
推荐回答(2个)
回答1:

#include
void main()
{
   FILE *fp;
   char ch;
   if((fp = fopen("test.txt","w"))==NULL)
   {
       printf("open file failed!\n");
       return ;
   }
   while((ch=getchar())!='#')
   {
       fputc(ch,fp);
       putchar(ch);
   }
   printf("\n");
   fclose(fp);
}

回答2:

#include
#include
#include
main()
{
FILE *fp;
char c;
if((fp=fopen("test.txt","w"))==NULL)
{ printf("can not open this file\n");
exit(0);
}
else
{
printf("input string,ending with #:\n");
c=getchar();
while(c!='#')
{
fputc(c,fp);
putchar(c);
c=getchar();
}
fclose(fp);
puts("\n");
}
}