Thursday, September 11, 2014

write text in a file using c language


Problem

Write a program that asks a user to enter file name to be created. If file is created successfully then display a message "File created" otherwise display error message and exit from program. Then program asks the user to enter any text to be written on that file. Output should be like:
  1. Enter the name of file: abc.txt
    File created
  2. Enter text for the file
    This is the new file...

Solution - Code

#include<stdio.h>
#include<stdlib.h>
int main ()
{
 char s[80],a[30];
 FILE *fp;

 printf ("Enter file name : ");
 gets (a);

 fp = fopen (a,"w");

 if (fp == NULL)
 {
  printf ("Not found");
  exit (0);
 }

 printf ("\n\nFile Created Successfully");

 printf ("\nNOTE: If you want to exit just press enter twice.\n\n");
 printf ("Enter Text : \n");

 while (strlen(gets(s)) > 0 )
 fputs (s,fp);

 fclose(fp);

 system("pause");
 return 0;
}

Sample Output

writing into file in c language

No comments :

Post a Comment

Note: Only a member of this blog may post a comment.

Copyright 2017. All Rights Reserved. Privacy Policy / Terms And Conditions / Sitemap / Contact