How to read multiple lines of input from user using fgets and write it into a file using fputs in C?

試著忘記壹切 提交于 2019-12-24 12:21:56

问题


I wanted to read input from user (multiple lines) and write it into a file using fputs().

Here is my code

#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;
}

After getting input from user, i am using Ctrl+C to close the input prompt of the program (I'm using linux). Then if i open the file, it contains nothing. How could I resolve this?

Is there anything wrong with the usage of fputs() & fgets()?


回答1:


Since C-C likely kills the process, because of buffering, the lines won't get to the file (unless there's a lot of them and they fill the buffer).

You should end the output with C-D (Unix) or C-Z (Dos), not C-C.

As a side note: fgets doesn't strip the newline and fputs adds its own. But I guess you were going to notice that :-)



来源:https://stackoverflow.com/questions/8147389/how-to-read-multiple-lines-of-input-from-user-using-fgets-and-write-it-into-a-fi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!