Tuesday, 25 November 2014

File Management in C Languge

Formatted Input in a file

#include<stdio.h>
#include<conio.h>
void main()
{
int roll,i;
char nm[10],ct[10];
FILE *ft;
clrscr();
ft=fopen("abc.doc","w");
for(i=1;i<=3;i++)
{
printf("Enter %d'st roll>> ",i);
scanf("%d",&roll);
fflush(stdin);
printf("Enter %d'st name>> ",i);
gets(nm);
fflush(stdin);
printf("Enter %d'st City>> ",i);
gets(ct);
fprintf(ft,e"%d\t%s\t%s\n",roll,nm,ct);
}
}


Reading a records from file to structure

#include<stdio.h>
#include<conio.h>
struct stu
{
int roll;
char nm[20];
char city[20];
};

void main()
{
struct stu ob;
FILE *ft;
clrscr();
ft=fopen("abc.doc","r");
while(fscanf(ft,"%d%s%s",ob.roll,ob.nm,ob.city)!=EOF)
printf("\n\tRoll=%d\tName=%s\tCity=%s\n",ob.roll,ob.nm,ob.city);
getch();
}

Write a block in a file

#include<stdio.h>
#include<conio.h>
typedef struct stu
{
int roll;
char name[10];
char city[10];
}student ;
void main()
{
int i,j;
student ob;
FILE *fp=fopen("a.txt","w");
clrscr();
printf("Enter how many records you want to enter>> ");
scanf("%d",&i);
for(j=1;j<=i;j++)
{
printf("Enter %d'st roll>> ",j);
scanf("%d",&ob.roll);
fflush(stdin);
printf("Enter %d'st Name>> ",j);
gets(ob.name);
fflush(stdin);
printf("Enter %d'st City>> ",j);
gets(ob.city);
fwrite(&ob,sizeof(ob),1,fpe);
}
}