Friday, 10 March 2017

C program for creating text file

Files are created and manipulated to store permanent data needed for a program. In C language, text files can be created and processed using file I/O functions. In the following program, we see how to create a new text file and open the created file and display the contents of the file on the screen.

//Program to create a text file
#include<stdio.h>
#include<conio.h>
main()
{
  FILE *f1;
  char c;
  clrscr();
  f1=fopen("sample.txt","w");
  printf("Enter text. Press ctrl+z to stop input\n");
  printf("----------------------------------------------\n");
 
  while ((c=getchar())!=EOF)
  fputc(c,f1);
  fclose(f1);

  printf("The content of the file\n");
  printf("--------------------------\n");
  f1=fopen("sample.txt","r");
  while((c=getc(f1))!=EOF)
  putchar(c);
  fclose(f1);
  getch();
}


/*
OUTPUT
-------
Enter text. Press ctrl+z to stop input
---------------------------------------------
This program creates a text file.                                              
The input is read from the keyboard.                                           
To stop getting input press ctrl+z.                                            
                                                                              
The content of the file                                                           
--------------------------                                                     
This program creates a text file.                                              
The input is read from the keyboard.                                           
To stop getting input press ctrl+z.
*/