Program to Create and Read a File

/* This program read a file entered by the user and displays its contents on the screen, fopen function is used to open a file it returns a pointer to structure FILE. FILE is a predefined structure in stdio.h . If the file is successfully opened then fopen returns a pointer to file and if it is unable to open a file then it returns NULL. fgetc function returns a character which is read from the file and fclose function closes the file. Opening a file means we bring file from disk to ram to perform operations on it. The file must be present in the directory in which the executable file of this code sis present.*/

 #include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

{

      FILE *fptr;

      int rl;

      char nm[20];

      char fname[20];

      long int tel;

      char ch;

      void line(void);

      clrscr();

      fptr=fopen(“data.dat”,”w”);

      do

      {

         printf(“\n”);

         printf(“Enter Roll No   :->”);

         scanf(“%d”,&rl);

         printf(“Enter Name      :-> “);

         fflush(stdin);

         gets(nm);

         printf(“enter Father’s  :-> “);

         fflush(stdin);

         gets(fname);

         printf(“Enter Telephone :-> “);

         scanf(“%ld”,&tel);

         fprintf(fptr,”%d %s %s %ld\n”,rl,nm,fname,tel);

         printf(“Enter any more record <<y/n>>?”);

         ch=getche();

      }

      while(ch==’y’);

      fclose(fptr);

      /* reading*/

      fptr=fopen(“data.dat”,”r”);

      printf(“\n”);

      line();

      while(!(feof(fptr)))

      {

           fscanf(fptr,”%d %s %s %ld\n”,&rl,nm,fname,&tel);

           printf(“%-7d %-20s %-20s %10ld\n”,rl,nm,fname,tel);

      }

      fclose(fptr);

      line();

      getch();

}

void line(void)

{

      int i;

      for(i=1;i<60;i++)

           printf(“*”);

      printf(“\n”);

}

Mohit Arora
Follow me