You are on page 1of 4

(http://www.studytonight.

com/)

C LANGUAGE

SEETHEINDEX

File Handling in C Language


Afilerepresentsasequenceofbytesonthediskwhereagroupofrelateddataisstored.Fileiscreatedforpermanentstorageofdata.Itisareadymade
structure.
InClanguage,weuseastructurepointeroffiletypetodeclareafile.
FILE*fp;

Cprovidesanumberoffunctionsthathelpstoperformbasicfileoperations.Followingarethefunctions,
Function

description

fopen()

createanewfileoropenaexistingfile

fclose()

closesafile

getc()

readsacharacterfromafile

putc()

writesacharactertoafile

fscanf()

readsasetofdatafromafile

fprintf()

writesasetofdatatoafile

getw()

readsaintegerfromafile

putw()

writesaintegertoafile

fseek()

setthepositiontodesirepoint

ftell()

givescurrentpositioninthefile

rewind()

setthepositiontothebeginingpoint

Opening a File or Creating a File


The fopen() functionisusedtocreateanewfileortoopenanexistingfile.
GeneralSyntax:
*fp=FILE*fopen(constchar*filename,constchar*mode);

Herefilenameisthenameofthefiletobeopenedandmodespecifiesthepurposeofopeningthefile.Modecanbeoffollowingtypes,
*fpistheFILEpointer( FILE*fp ),whichwillholdthereferencetotheopened(orcreated)file.
mode

description

opensatextfileinreadingmode

opensorcreateatextfileinwritingmode.

opensatextfileinappendmode

r+

opensatextfileinbothreadingandwritingmode

w+

opensatextfileinbothreadingandwritingmode

a+

opensatextfileinbothreadingandwritingmode

rb

opensabinaryfileinreadingmode

wb

opensorcreateabinaryfileinwritingmode

ab

opensabinaryfileinappendmode

rb+

opensabinaryfileinbothreadingandwritingmode

wb+

opensabinaryfileinbothreadingandwritingmode

ab+

opensabinaryfileinbothreadingandwritingmode

Closing a File
The fclose() functionisusedtocloseanalreadyopenedfile.
GeneralSyntax:
intfclose(FILE*fp);

Herefclose()functionclosesthefileandreturnszeroonsuccess,orEOFifthereisanerrorinclosingthefile.ThisEOFisaconstantdefinedintheheader
filestdio.h.

Input/Output operation on File


IntheabovetablewehavediscussedaboutvariousfileI/Ofunctionstoperformreadingandwritingonfile. getc() and putc() aresimplestfunctionsused
toreadandwriteindividualcharacterstoafile.
#include<stdio.h>
#include<conio.h>
main()
{
FILE*fp;
charch;
fp=fopen("one.txt","w");
printf("Enterdata");
while((ch=getchar())!=EOF){
putc(ch,fp);
}
fclose(fp);
fp=fopen("one.txt","r");

while((ch=getc(fp)!=EOF)
printf("%c",ch);

fclose(fp);
}

Reading and Writing from File using fprintf() and fscanf()

#include<stdio.h>
#include<conio.h>
structemp
{
charname[10];
intage;
};

voidmain()
{
structempe;
FILE*p,*q;
p=fopen("one.txt","a");
q=fopen("one.txt","r");
printf("EnterNameandAge");
scanf("%s%d",e.name,&e.age);
fprintf(p,"%s%d",e.name,e.age);
fclose(p);
do
{
fscanf(q,"%s%d",e.name,e.age);
printf("%s%d",e.name,e.age);
}
while(!feof(q));
getch();
}

Inthisprogram,wehavecreatetwoFILEpointersandbotharereferingtothesamefilebutindifferentmodes.fprintf()functiondirectlywritesintothefile,
whilefscanf()readsfromthefile,whichcanthenbeprintedonconsoleusinfstandardprintf()function.

Difference between Append and Write Mode


Write(w)modeandAppend(a)mode,whileopeningafilearealmostthesame.Bothareusedtowriteinafile.Inboththemodes,newfileiscreatedifit
doesn'texistsalready.
Theonlydifferencetheyhaveis,whenyouopenafileinthewritemode,thefileisreset,resultingindeletionofanydataalreadypresentinthefile.Whilein
appendmodethiswillnothappen.Appendmodeisusedtoappendoradddatatotheexistingdataoffile(ifany).Hence,whenyouopenafileinAppend(a)
mode,thecursorispositionedattheendofthepresentdatainthefile.

Reading and Writing in a Binary File


ABinaryfileissimilartothetextfile,butitcontainsonlylargenumericaldata.TheOpeningmodesarementionedinthetableforopeningmodesabove.
fread()andfwrite()functionsareusedtoreadandwriteisabinaryfile.
fwrite(dataelementtobewritten,size_of_elements,

number_of_elements,pointertofile);

fread()isalsousedinthesameway,withthesameargumentslikefwrite()function.Belowmentionedisasimpleexampleofwritingintoabinaryfile
constchar*mytext="Thequickbrownfoxjumpsoverthelazydog";
FILE*bfp=fopen("test.txt","wb");
if(bfp){
fwrite(mytext,sizeof(char),strlen(mytext),bfp);
fclose(bfp);
}

fseek(), ftell() and rewind() functions


fseek()Itisusedtomovethereadingcontroltodifferentpositionsusingfseekfunction.
ftell()Ittellsthebytelocationofcurrentpositionofcursorinfilepointer.
rewind()Itmovesthecontroltobeginningofthefile.

Some File Handling Program Examples

CreateaFileandStoreInformationinit(programtowriteinfile.php)
ListalltheFilespresentinaDirectory(programtolistfilesindirectory.php)
FindingSizeofaFile(programtofindsizeoffile.php)
CopyContentofoneFileintoAnotherFile(programcopyfiletoanotherfile.php)
ReversetheContentofFileandPrintit(programtoreversecontentoffile.php)

Prev(pointerwithfunctioninc.php)

Next(errorhandlinginc.php)

You might also like