Showing posts with label FILE HANDLING. Show all posts
Showing posts with label FILE HANDLING. Show all posts

Monday, 23 February 2015

FILE HANDLING IN C


File
=====

File Handling In C is Very Simple. As it essentially Treats a File as Just Stream of Characters and accordingly allows to input and output to the file.

Steps To Handle a File
=======================

1) Open The File
2) Access The File
3) Close The File

Syntax For To Declare a File Pointer
====================================

FILE *p;

p=fopen("FileName","Mode");


Mode
====
r - ReadMode
w - WriteMode
a - AppendMode

r+ - Read+Write
w+ - Write+Read
a+ - Append+Read

File Handling Functions
========================

Character Oriented Functions
============================
1) fgetc()
2) fputc()

String Oriented Functions
============================
1) fgets()
2) fputs()

Reading & Writing Records To The File
=====================================
1) fwrite()
2) fread()

Formatted IO Functions
============================
1) fprintf()
2) fscanf()

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();
}