fgets(), fputs() - Line Input and Output - sample program in C

By: Reema sen  

The standard library provides an input and output routine fgets that is similar to the getline function"
   char *fgets(char *line, int maxline, FILE *fp)
fgets reads the next input line (including the newline) from file fp into the character array line; at most maxline-1 characters will be read. The resulting line is terminated with '\0'. Normally fgets returns line; on end of file or error it returns NULL. (Our getline returns the line length, which is a more useful value; zero means end of file.)

For output, the function fputs writes a string (which need not contain a newline) to a file:

   int fputs(char *line, FILE *fp)
It returns EOF if an error occurs, and non-negative otherwise.

The library functions gets and puts are similar to fgets and fputs, but operate on stdin and stdout. Confusingly, gets deletes the terminating '\n', and puts adds it.

To show that there is nothing special about functions like fgets and fputs, here they are, copied from the standard library on our system:

   /* fgets:  get at most n chars from iop */
   char *fgets(char *s, int n, FILE *iop)
   {
       register int c;
       register char *cs;

       cs = s;
       while (--n > 0 && (c = getc(iop)) != EOF)
           if ((*cs++ = c) == '\n')
               break;
       *cs = '\0';
       return (c == EOF && cs == s) ? NULL : s;
   }

   /* fputs:  put string s on file iop */
   int fputs(char *s, FILE *iop)
   {
       int c;

       while (c = *s++)
           putc(c, iop);
       return ferror(iop) ? EOF : 0;
   }
For no obvious reason, the standard specifies different return values for ferror and fputs.

It is easy to implement our getline from fgets:

   /* getline:  read a line, return length */
   int getline(char *line, int max)
   {
       if (fgets(line, max, stdin) == NULL)
           return 0;
       else
           return strlen(line);
   }



Archived Comments

1. yoyo honey singh
View Tutorial          By: suos at 2014-12-23 11:34:33

2. Wynn documented revenue before last number of quartersit could possibly preserve stagnating, or mayb
View Tutorial          By: Smithd507 at 2014-05-24 14:02:01

3. if (fget(y,100,fp2)!=10);
what should be the prototype for this.
plzz reply fast.

View Tutorial          By: ruqsar at 2014-02-10 10:54:32

4. for: not to use conditions
while: you can.

View Tutorial          By: Manuel at 2012-07-16 04:58:44

5. /*for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;*/
View Tutorial          By: GD at 2012-07-14 12:47:27

6. hiiiiiiii
View Tutorial          By: venkateshwarreddy suravaram at 2010-04-30 23:57:01


Most Viewed Articles (in C )

Latest Articles (in C)

Comment on this tutorial