Writing to a File in C Programming

To write on a file there are following  function available:

  1.  Function fputc() : function fputc() write individual characters at a time to the file. The syntax of this function is –

Syntax :

               int  fputc( int c,  FILE *fp );

Function fputc()  returns the written character written on success and  if there is an error it will return EOF (Emd of File).

  • Function fputs() :  function fputs() writes the string s’ to the output stream referenced by fp. The syntax of this function is –

Syntax :

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

Function fputs()  returns the non-negative value  on success and  if there is an error it will return EOF (Emd of File).

  • Function fprintf(): Function fprintf()write a string into a file. The syntax of this function is –

Syntax :

int  fprintf(FILE  *fp,  const  char *format, …)

Example: Write a C program to write a single character into file using fputc() function in file handling.

#include 
int main() 
{
   FILE *fp;

   fp = fopen("c/Book1.txt", "w+");  			 //opening file Book1.txt for write 
   fprintf(fp, "Hello  hii  how are you \n");     		//write a string into file Book1.txt 
   fputs("I am aditya  \n", fp);         			//write a string into file Book1.txt
   fclose(fp);              					//closing file  
}

OUTPUT

a
BOOK1.txt

 Example: Write a C program to write a string into a file using fputs() and fprintf() function in file handling.

#include 
int main() 
{
   FILE *fp;

   fp = fopen("c/Book1.txt", "w+");  			 //opening file Book1.txt for write 
   fprintf(fp, "Hello  hii  how are you \n");     		//write a string into file Book1.txt 
   fputs("I am aditya  \n", fp);         			//write a string into file Book1.txt
   fclose(fp);              					//closing file  
}

OUTPUT

Hello  hii  how are you
I am aditya

Book1.txt

Description: When  we run the above program , it creates a new file Book1.txt in /c directory and writes two lines using fputs() and fprintf() functions.

Example : Write a C program to open a file, write in it and close the file.

# include  
# include 
int main( ) 
{ 
      FILE *fp ;     			 			// Declare the file pointer fp
    char str[30] = "i am aditya from it department"; 		 // data to be written in file 
        
    fp = fopen("Book1.txt", "w") ;    			  // Open file Book1.txt using for write
      
    if ( fp == NULL )           				// Check if this filePointer is null 
    { 
        printf( "failed to open file" ) ; 
    } 
    else
    { 	 printf("The file is now opened.\n") ; 
          
            	 if ( strlen (  str  ) > 0 ) 		// check the length of data >0
        		{ 
     			fputs(str, fp) ;     // writing in the file using fputs() 
            		fputs("\n", fp) ; 
        		} 
          
        fclose(fp) ;		// closing file  
        printf("The file is now closed.") ; 
    } 
    return 0;         
}

  OUTPUT

i am aditya from it department

Book1.txt