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

StackOverflow https://stackoverflow.com/questions/8147389

  •  02-03-2021
  •  | 
  •  

Pregunta

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()?

¿Fue útil?

Solución

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 :-)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top