【问题标题】:How to read multiple lines of input from user using fgets and write it into a file using fputs in C?如何使用 fgets 从用户读取多行输入并使用 C 中的 fputs 将其写入文件?
【发布时间】:2011-11-16 06:01:19
【问题描述】:

我想读取用户的输入(多行)并使用 fputs() 将其写入文件。

这是我的代码

#include<stdio.h>
#include<stdlib.h>
int main()
{
 FILE *fp;
 char s[25];
 fp=fopen("myname","w");
 if(fp==NULL)
 {
  perror("Error opening file\n");
  exit(1);
 }

 while(fgets(s,25,stdin)!=NULL)
  fputs(s,fp);
 fclose(fp);
 return 0;
}

得到用户的输入后,我使用 Ctrl+C 关闭程序的输入提示(我使用的是 linux)。然后,如果我打开文件,它什么都不包含。我该如何解决这个问题?

fputs() & fgets() 的使用有什么问题吗?

【问题讨论】:

  • 您的代码将中断 25 个字节的行。您可以使用fgets(s, sizeof(s)-1, stdin) 并且之前使用memeset(s, 0, sizeof(s)); 会更好。而getline 是一个更好的函数(因为它动态分配线路)。
  • @BasileStarynkevitch,fgets 的手册页上写着fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s..... A '\0' is stored after the last character in the buffer。因此,在fgets() 通话中使用 25 是安全的。我用超过 25 个字符的行测试了这段代码。不工作的原因是缓冲。添加fflush(fp) 解决了它。抱歉迟到了评论。

标签: c file fgets fputs


【解决方案1】:

由于C-C 可能会终止进程,因为缓冲,行不会到达文件(除非有很多行并且它们填满了缓冲区)。

您应该以C-D (Unix) 或C-Z (Dos) 结束输出,而不是C-C

附带说明:fgets 不会删除换行符,fputs 会添加自己的换行符。但我想你会注意到 :-)

【讨论】:

  • 谢谢哥们,你是对的。现在我',得到正确的输出:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
  • 2020-02-20
  • 2021-03-23
  • 1970-01-01
  • 2011-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多