A C Program To Write 5 Elements To a File

26 March 20120 comments

To write a block of data into a file , the syntax is
                            fwrite(ptr , m , n , fp)
Where ptr is an address of array or structure to be written into the file , m is the size of the array , n is the number of structures or arrays to be written and fp is the file pointer.

Following program demonstrate how to write an array onto a file.
  1. #include<stdio.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5.     FILE *fp;
  6.     int a[5],i;
  7.     clrscr();
  8.     if((fp=fopen("text1.dat","wb"))==NULL)
  9.     {
  10.         printf("\n Cannot open file");
  11.         exit(1);
  12.     }
  13.     printf("\n Enter five numbers");
  14.     for(i=0;i<5;i++)
  15.        scanf("%d",&a[i]);
  16.     fwrite(a,sizeof(a),1,fp);
  17.     fclose(fp);
  18. }
  19.      
Tags: C programming examples , Programs on file handling in C , Programming exercise on file in C , How to write an array into the file in C , How to write a structure into the file in C
Share this article :

Post a Comment

 
Copyright © 2011. All Compiler - All Rights Reserved