0% found this document useful (0 votes)
114 views

File Handling in C Language - C Language Tutorial - Studytonight

This document discusses file handling in C language, including how to open, read from, write to, and close files using functions like fopen(), fclose(), fread(), fwrite(), and more. It explains the differences between reading/writing text files and binary files, and between opening files in write versus append mode. Examples are provided of common file handling operations like reading/writing data, characters, and structures to and from files.

Uploaded by

Ravi Singh Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views

File Handling in C Language - C Language Tutorial - Studytonight

This document discusses file handling in C language, including how to open, read from, write to, and close files using functions like fopen(), fclose(), fread(), fwrite(), and more. It explains the differences between reading/writing text files and binary files, and between opening files in write versus append mode. Examples are provided of common file handling operations like reading/writing data, characters, and structures to and from files.

Uploaded by

Ravi Singh Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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