file-handling

File handling

The processing of a file involves the following steps:

  • opening a file
  • reading or writing a file
  • closing a file

Opening a file: Opening a file establish a link between the program and the operating system.

FILE *fp;

Where file is the data structure included in stdio.h and fp is file pointer which points to the start of the file.

opening a file
fp=fopen(“filename”,”mode”);
Where fp is pointer to structure of type FILE.
closing a file, fclose(fp);

Program to enter data of mixed types in a file

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch=’y’,name[20];
int age;
float salary;
clrscr();
if((fp=fopen(“test4.dat”,”w”))==NULL)
{
printf(“\n Cannot open file”);
exit(1);
}
while(ch==’y’)
{
printf(“enter name,age and salary “);
scanf(“%s%d%f”,name,&age,&salary);
fprintf(fp,”%s\t%d\t%f\n”,name,age,salary);
printf(“\n More records(y/n)?”);
ch=tolower(getche());
}
fclose(fp);
}

enter name, age and salary: devilson 23 444444

more record (y/n)?