Monday 23 February 2015

File Handling in C



Fopen()
Fprintf()
Fscanf()
Fclose()

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
Char name[40];
Char ans=’y’;
Int age;
Float bs;
Clrscr();
Fp=fopen(“EMPLOYEE.DAT”,”w”);
If(fp==NULL)
{
printf(“Cannot open file”);
exit();
}
while(ans= =’Y’ || ans= =’y’)
{
printf(“\n Enter name, age and basic salary:\n”);
scanf(“%s%d%f”,name,&age,&bs);
fprintf(fp,”%s%d%f\n”,name,age,bs);
printf(“\n Another employee(y/n)”);
scanf(“%c”,&ans);
}
fclose(fp);
}

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
Char name[40];
Int age;
Float bs;
Clrscr();
Fp=fopen(“EMPLOYEE.DAT”,”r”);
If(fp==NULL)
{
printf(“Cannot open file”);
exit(0);
}
while(fscanf(fp,”%s%d%f”,&name,&age,&bs)        != EOF)
printf(“\n %s%d%f”,name,age,bs);
fclose(fp);
}

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *infile;
Char name[20];
Char street[20];
Char city[15];
Char pin[7];
Int cho=1;
Char s[20];
Clrscr();
Printf(“File Name?\n”);
Scanf(“%s”,&s);
Infile=fopen(s,”a”);
While(cho==1)
{
printf(“\n Type your name:”);
scanf(“%s”,&name);
printf(“\n Type your street name:”);
scanf(“%s”,&street);
printf(“\n Type your city name:”);
scanf(“%s”,&city);
printf(“\n Type your pincode:”);
scanf(“%s”,&pin);
fprintf(infile,”%s\t”,name);
fprintf(infile,”%s\t”,street);
fprintf(infile,”%s\t”,city);
fprintf(infile,”%s\t”,pin);
fprintf(infile,”\n”);
printf(“Enter 1 to continue:”);
scanf(“%d”,&cho);
}
fclose(infile);
}

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *infile;
Char name[20];
Char street[20];
Char city[15];
Char pin[7];
Char s[20];
Clrscr();
Printf(“File Name?\n”);
Scanf(“%s”,&s);
If((infile=fopen(s,”r”))=NULL)
{
printf(“Cannot open file”);
exit();
}
while(fscanf(infile,”%s%s%s%s”,name,street,city,pin)!=EOF)
{
printf(“\n Name:%s\t”,name);
printf(“\n Street:%s\t”,street);
printf(“\n City:%s\t”,city);
printf(“\n Pin:”%s\t”,pin);
printf(“\n”);
}
fclose(infile);
getch();
}

No comments:

Post a Comment