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.

OUTPUT

a
BOOK1.txt

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

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.

  OUTPUT

i am aditya from it department

Book1.txt