fgets() and fputs() functions in C - C-Tutorial

Latest

Thursday, 10 November 2016

fgets() and fputs() functions in C

 fgets() and  fputs() functions in C


            fgets() and fputs() functions are string oriented functions that can be handled an entire line as a string at a time.

fgets() function:                      fgets() function is used to read a set of characters as a string from a given file.  The general format of the fgets() function is:

            Syntax:            fgets(char[], int, FilePointer);
Where,
            The first argument is the character array where the string is stored.
            The second argument is the maximum size of the string.
            The third argument is the FilePointer of the file to be read.
The function returns a NULL pointer if the end of file has been reached.

fputs() function:          fputs() function is used to write a string into a file.  The general format of the fputs() function is:

            Syntax:            fputs(char[], FilePointer);

Where,
            The first argument is the character array to be written into the file.
            The second argument is the FilePointer of the file to write.
The function returns a non-negative value on successful completion; otherwise, it returns EOF.

/* COPY THE CONTENTS OF ONE FILE TO ANOTHER FILE LINE BY LINE */

#include<stdio.h>
#include<string.h>
main()
{
            char ch[50];
            FILE *fp1,*fp2;
            clrscr();
            fp1=fopen("check.txt","r");
            if(fp1==NULL)
            {
                        printf("\nFILE OPENING ERROR");
                        exit();
            }

            fp2=fopen("ptr.txt","w");
            while((fgets(ch,sizeof(ch),fp1))!=NULL)
            fputs(ch,fp2);
            fclose(fp2);
            fclose(fp1);

}

No comments:

Post a Comment