C program to write a string to text file

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 :");
  // Read string to write
  printf("Enter the string to write :");
   // Open file in write mode
   fp = fopen(filename,"w+");

   // If file opened successfully, then write the string to file
   if ( fp )
         printf("Failed to open the file\n");
//Close the file

Post a comment


Your Comment

Email (We dont publish it)


Nothing yet..be the first to share wisdom.