File Handling in C Language - C Language Tutorial - Studytonight
File Handling in C Language - C Language Tutorial - Studytonight
com/)
C LANGUAGE
SEETHEINDEX
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
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.
while((ch=getc(fp)!=EOF)
printf("%c",ch);
fclose(fp);
}
#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.
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);
}
CreateaFileandStoreInformationinit(programtowriteinfile.php)
ListalltheFilespresentinaDirectory(programtolistfilesindirectory.php)
FindingSizeofaFile(programtofindsizeoffile.php)
CopyContentofoneFileintoAnotherFile(programcopyfiletoanotherfile.php)
ReversetheContentofFileandPrintit(programtoreversecontentoffile.php)
Prev(pointerwithfunctioninc.php)
Next(errorhandlinginc.php)