1

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

Dinesh
  • 16,014
  • 23
  • 80
  • 122
  • Your code will break for lines of 25 bytes. You could use `fgets(s, sizeof(s)-1, stdin)` and you'll better `memeset(s, 0, sizeof(s));` before. And `getline` is a better function for this (because it allocates the line dynamically). – Basile Starynkevitch Nov 16 '11 at 06:08
  • @BasileStarynkevitch, the man page for `fgets` says `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`. So, it is safe to have 25 in `fgets()` call. I tested this code with lines longer than 25 chars. The reason for not working is buffering. Adding `fflush(fp)` solved it. Sorry for the late comment. – Bhaskar Mar 12 '12 at 11:32

1 Answers1

3

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

cnicutar
  • 178,505
  • 25
  • 365
  • 392