Reading and writing a character from a file using fputs, fgets,

The fputs() function

The fputs() function is used to write string(array of characters) to the file.

Syntax of fputs() function

              fputs(char str[], FILE *fp);

The fputs() function takes two arguments, first is the string to be written to the file and second is the file pointer where the string will be written.

Example of fputs() function

       #include<stdio.h>

       void main()
       {
              FILE *fp;
              char str[];

              fp = fopen("file.txt","w");            //Statement   1

              if(fp == NULL)
              {
                     printf("\nCan't open file or file doesn't exist.");
                     exit(0);
              }

              do
              {
                     gets(str);
                     fputs(str,fp);

              }while(strlen(str)!=0);


              printf("\nData written successfully...");

              fclose(fp);
       }

   Output :

              C is a general-purpose programming language.↩
              It is developed by Dennis Ritchie.↩
              ↩
              Data written successfully...

In the above example, statement 1 will create a file named file1.txt in write mode. Statement 2 is a loop, which take strings from user and write the strings to the file, until user input an empty string.

The fgets() function

The fgets() function is used to read string(array of characters) from the file.

Syntax of fgets() function

              fgets(char str[],int n,FILE *fp);

The fgets() function takes three arguments, first is the string read from the file, second is size of string(character array) and third is the file pointer from where the string will be read. 
The fgets() function will return NULL value when it reads EOF(end-of-file).

Example of fgets() function

       #include<stdio.h>

       void main()
       {
              FILE *fp;
              char str[80];

              fp = fopen("file.txt","r");            //Statement   1

              if(fp == NULL)
              {
                     printf("\nCan't open file or file doesn't exist.");
                     exit(0);
              }

              printf("\nData in file...\n");

              while((fgets(str,80,fp))!=NULL)
                     printf("%s",str);

              fclose(fp);
       }

   Output :

              Data in file...

              C is a general-purpose programming language.
              It is developed by Dennis Ritchie.

In the above example, statement 1 will open a file named file.txt in read mode. Statement 2 is a loop, which take strings from file and write the string to console until it reaches to the EOF(end-of-file).