by Dinesh Thakur Category: File Handling

The fgets function reads a sequence of character, i. e., a character string from an input stream. Its prototype is given below.

char *fgets(char *s , int n, FILE*fp);

The characters from the input stream are read into a character arrays until a newline character is read, n - 1 characters are read or the end-of-file is reached. If a newline character is read, it is retained in the character array. The function then adds a terminating null character to strings and returns it. However, the function returns a NULL value if an end-of-file is encountered before any character is read or an error occurs during input.

The fputs function writes a character string to an output stream. Its format is given below.

int fputs (const char *s , FILE *.fp) ;

All the characters in strings except the null terminator are written to stream fp. The function returns the numbers of characters written to the stream or EOF if an error occurs during output.

These functions are similar to putchar () and getchar () which we have already used for standard input/output. The functions may also be used for standard input/output by changing the file stream. The header file <stdio.h> should be included in the program which uses these functions.

A program to display a specified text file using the fgets and fputs functions is given below.

#include <stdio.h>
#include <stdlib.h>
void main()
{
  //Header fileincluded for function exit()
  FILE* Fptr;
  char ch;
  Fptr = fopen("Myfile","w");
  clrscr();
  if(Fptr ==NULL)
      //open myfilefor writing.
     // If return value is NULL exit
    {
      printf("File could not be opened.");
      exit (1);
    }
  else
   {
      printf("File is open. Enter the text.\n");
      while ((ch= getchar()) != EOF) /*get characters from keyboard*
      fputc(ch, Fptr); //one by one and write it to file.
      fclose(Fptr);
    } //this code closes the file
    Fptr = fopen("Myfile","r"); // open file for reading
    if(Fptr ==NULL) // if return value is NULL, exit.
      {
         printf("File could not be opened");
         exit(1);
      }
    else
        {
           printf("File is opened again for reading.\n");
           while ((ch= fgetc(Fptr)) != EOF) // get characters from file
             printf("%c",ch);
             fclose(Fptr);
        }  // till EOF and display it.
}          // This line closes the file.

The expected output is as given below. The EOF is included by pressing Ctrl and Z. It is indicated by ^Z in the third line of output.

 The fgets and fputs Functions in C



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.