C program to write a string to text file

Last updated on 06th January 2016

This is a C program to write to text file.

The user is prompted to enter the name of the file to write to and also the string that has to be written. If the specified file already exists then it will be overwritten. The filename is passed as the first parameter to the fopen() function. The second parameter of fopen() function is w+ which means to open the file for reading and writing.

The fopen() function return a pointer to the FILE stream which is then used with the fputs() function to write the string to the file.

Program Source

/*************************************************
 * C program to write a string to a file	 *
 *************************************************/

#include <stdio.h>

int main()
{
 FILE *fp;
 char filename[100];
 char writestr[100];

  // Read filename
  printf("Enter a filename :");
  gets(filename);
  
  // Read string to write
  printf("Enter the string to write :");
  gets(writestr);
  
   // Open file in write mode
   fp = fopen(filename,"w+");

   // If file opened successfully, then write the string to file
   if ( fp )
   {
	   fputs(writestr,fp);
    }
   else
      {
         printf("Failed to open the file\n");
        }
//Close the file
   fclose(fp);
return(0);
}

Also Read


Post a comment

Comments

Nothing yet..be the first to share wisdom.