0% found this document useful (0 votes)
11 views14 pages

Assignment 5 Cse

Uploaded by

avneeshumang2005
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)
11 views14 pages

Assignment 5 Cse

Uploaded by

avneeshumang2005
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/ 14

AssIGNMENT- 5 CSE 113]

Defne strwetwes and njond C. Enplain


n C. tthe
declaration and ditfenences between them.
Ae Stwctwres in C:
Strwctues alla yon to gio vasjables of diffeset
data typu wele
Menbe of be a cceted wmg the
dot (^) operatn
Declartion:
stuct Studet
t l| Nurbea;
cha name [s])
float mantij

Unions in
Unions, ke stwctwe, allo gou to gop vasiabley
of dffoent dat yres.
wcli memosy as the ayest
ynemben, wheeas s4wtes
) e memory egual to fhe dm
of hein menbers.
ymember of a ion Cau be
accesÇe d t a
tme
Declation
Unen Value

flont foatnlue;

Ditfenneu byw Strwctne and


1. Mermoy Allocaton;
Strwctues: allocote merory for each menber depndety
Vwions : shne memey anog all members.
2. Acee ssing Mebens i 4ccesJed
Stowctwes: Menbeu ae
member be acceted at a fie.
One

when ifferet pieces of ihfouaton need


Sstnwctwes: whed
to be sored siltecuy:
Uion: wed when piece of infmation meesls
ondy
to loe Ngored at a time, buct he tyc may vay.

Yhow dlo CAeate aag of strwetue m c?


rotde practcal aplication.
of stwctes in C
Geatig
defadt strwcte nd ten declag
of that stowctuoe tye.
Cistudents
3. o.2f\n", Manks: prntf
("
manks); pridf
i].mameJ; stuents %s\n", Name: ("
d
\n", undben: Roll pritt(
n; Ci].rll stvdents Cint for
it+)
{ i<3; iz0;
[2].manks=48.3j studet
nane," (stodents
(21. strepy
Tohnion"); Bob
lo3j Nunten roll (2].Studect
92.0; maks= [1).student
(students
C11. stncpy
nita"}; "Jane nane,
Jo2;nol|Nunben [1].studets
Co).marts Studets
nane,stncpy(sfudet
85.5j [o]. =
Doe"J; "Joun
ollNumden=
Jol; [o].Student
studets
(3] ; Studet strwet
ma() int
maks; float
[so] name cun
Munbenj rol nt
Studetf stowet
<stdio.h> #include
Declarati:
Union alue

float floatalue ;
chs sthyvalue [2o3;

Differnees b/w Strwctne and


1 Memo Allocatron ;
Stnwctes: allocnte meny fon en ch menbes jndepdetg
all menbend .c

2. Aceessng Mebens i g the (o).


Strwctes: Menbeu re accessed helimdaly
member be accened at
. Umoms: One

3 Vsage of ihfonatien need


Strwteti Wed when diffenet pieces
o be Stored iltaneouy.
" Uniona: wed when on One piece of infention meesls
to lbe NAored at a tine, buct the tye mag vay.

Q2 Yow clo you Create of stwetue M C?


lraide a practical opplicahin.
Geatg an
ay of srwtes in c jeld
sfrwcte then declag
defig a
of tluat skwe
strwctee tye.
concept of a
ud 1/o theanig
n C, fles a e wjed fo) input nd output
Dfetios. A 6les collecton of data sforet
Sfeuge
medium, tvch as hand doive
a Payli dee. n C, the stdio, h bay proydes
fctou fon fle operatow.
Concept of a Recond:
a colleetion of elated dat iter!
4neated as eco
often the Rmallest nit ot clatq that head
from Lwite to file.
fon exanple, f menging infonation abrot
Yvelet dotlu Cou lo Conidened a ecosd

h C, input ( output operatioud penfrmed


A stream
1/0 sAncandng in c iuolies the flow of cat bytei.
lbetween
output fnctios Uie wyed fon
ud from files. srearg dat to
enable data perHistence,
suprgeut stwctwed
cod colleetion of data,
I/0o strean iwobed he anster of data
fle operatiy ertewvl stonage
between tyes f kles i inolered fles,
random
Sequentinl files and
tfeereut pen of filea feue
distnt pepose;
1. Seqehial Ale :
Chargtenistics - Dati Stored in a linean equutial
Onde.
" Access Pattery Read on wrte operationg 0cun
from he begtng to the end of tue fle.
Aduantoe- hmple and eay to irpleret. suitable fon
tasks whne dat is proceiied in a inea mannen.
isadvantayes netfciert ton dineet CCEeS

modihicato at bitray pontions.


tndered hles:
dhnacterietes - Dasta foned teyuentinly, bnt an index
Js mantaned fon dinect acces.
" Acces latten - Allow fon both Pegieuel ont dheet
acces jles trwcchore.
Advantages- enables quick aces
withott readig the entne Kle seg ventially
Dis advatages - More comglex due to the maitenance
ndey. be len ethuent fon eentl operation
comparel o 4equenht fle
Random fle:
Chanatenitties Supporct chet acceH to any record
without te need for segetal roceshig
" Access latte- allaw dirt acce necord! based
pecithc potition and
Adrtes- efkcieut fon both equentl dinect acces

PSadvantges ypically jole mene compler implementaton


compred to tegvental kles
between tyes of fles inolered flee,
fles and ranlom filer.
Sequental
C proyamhg, lfeneut types of flee feue
diitmet pepoe:
1. Sequeutial Ale :
Chargctenisties - Dati is S4ored in a linean teuential
0nde.
" Access Pattey- Read on wite opeatons 0cewn squedtilly
frem the beginnig to the end of the file.
Adiantoes- mple and eany to irlerat. tuitable fon
fases dat is paocesied n a inea manne.

isadvantages- hetfkeiat for dinet


madihcatoy at abtitr poaitio.
tndexed hles:
caraterietes - Desta but ay index
Js mataned fon dinect access
Acces Patten - Allow fon both
j'ne twcte.
Advantges- enables quck ouces to pe aifie ecod!
withot Aeadg the enre fle
Disadrantag- ore comples due to thetequetd
be len e thidevt fon
maiteiane of
indey. opoahon
companed to eqrended Aler
B Randam fle: record
Chanateniahes Support dineet accen to ong
witout the meed fon seyvetal poceting
. Acceus fatteu- lla iet acce o necondi byed
opecihe potiton
" Adtges- efkeent fon both mauental and diect
hutase fon taks egnung nanom data ndia
acces

compla inmplameatadie
corpred to tequenhal fles.
05 fle in C?
Houw you Ceate a clata
Explin the pro cets
dote 7le jn C mres the fle .
wite nead and lee
9ndown:
baic
data fle in C:
Steps to Create a

nclude meceha Libraes


finclude < stdio. h> || fen file openatond
2. Detne a fle pointor: iuteat ith fle
will be ued to
FILE flePointen;

foren ("4lename.txt""w");
fon witg 34 the file alneny
Ymode Csietes a new fle
contents .
exts -

Loil ovEwste i
mode ted to exiating fle.
" "a"
4 Wite clat fprintt ()' n fptel)':
to the fle
data.ln"J;
fprintt (flkfcinte,Ths is one
l on using fpute :
flefointen);
I| fputc ('H',Alelointen );
I| fpute ('i,
felose ()' :
lose he Ale Using
fclore (-fleloindend;
S4 esetal to dose he file aftor you ae done.
from it. This
sICnding sared and 1er0wces neleased.
Exgmple
incuele <stolio. h>
jvet man ()
FILE *flefointerj
"w");
flefointen = foren (" data.txt",
if (flefoinden
peunct ("hle could not be opened."J;

Some dataln"):
teintt ( flelointen, "Thit is
fle in C is sirple!\n"
fpointt ( flefointen ,"Wstig to a
fclose (fle Pointen;

Biscws he opentin nnaled in openi clong


and mauipulang data fle.
6le:
Dpening
fopen l)' fle and estalt a conne tion blu
fuyose- o open q
he Ale and fle pointer.
Syndax- FILE fopenl cowst ehan *flenane, cont chas *ode);
f'lemare - Name of the fle to be opened.
mode - peike te poOe of fle acceM Like eadng
wwring, ppendg te.. (eijy "n", w, "a", "a+", "w", a+").
Gle :
Closing
flose () anel e r e
"Pyose-o clore n Opened file to nelease neorce
data intgt FILE *Alefointen);
Syntar- int fcloe (
" flePoivten- The poiter to the file to be clored.
Reactfs canfing ),
Data from
fgets(), fread)
a ile :

"Puopore
Synt
To cacl clata frem an opencd tile

inct fscanf (fILE * flefointen, cont chay t forat,...))


" chai
gets ( chn *tn, int n, fiLE *Aeojnter
*Size t fnca (vold *pta. ze-t size ie-t mmenb, fILE **lefointen);
fs cant() nca fotmatied data , fets() 9eads L'ne of text,
freadl ncacd a block of data.

Witing
fprintf (),
Data to 9 fle :
fputs (), fwnitel.
furpose- To write data to an opened fle.
" Syntax
"int fpintf( FiLE *flefoider, const chan *format,- );
" int fputs ( cot ch *s4, fILE
**lelointer);
" Sizet fwrte ( cowt void *pta, i2e-t size, G2et nnonb,
FILE *ktelointor
fprintflU wites formated data, fput () wnites a
block of data.
Moing within a file:
fseekl), reindJ
Rnpoe the move
fle.
the fle polnter to a tpe
eie locaton withn
Synty
.jnt fseck (FILE * kfomter ,
" yoid ewind Long offset ,mt whence);
(fILE *fle Poircde:
fseekl) allow ndom Qccest
baed ou
9eindl) move
'henee' Cstt, cnet, on end of ifle).
opecified poiton
the pointen to
the begtnng of the fle.
defnes a
C Pogam that Mwcte
huelent jnfoaon (name, roll unben
to repesent
ama maes ound ntorcs t in a file.
Au ttinclude <stdio.hs
# include < stellib.h>
stvct Studet
chas name (so];

flot j

ivt ymain(){
strwct stvotet stutect ; || Creade a vawahe of type student
I| Get stvelent infomatian forom tue uyer
poivtf ("Eter stolenct ane ; ";
fgett (student. name, i2e of (student.mame), stin);
p9untt "te oll mumter: "},
Scant (od", k studet. oll Mnben );
privet f (" ter ks:");
scant (%d", stvdet. maksJ;
a le in wtt noee
FILE *6lefoinen;
flefointen - fopen ( "studet info. 4xt", "w;
Il check if the file was openet fucestly
if (AlePoindea= NULL)
pritt ("sovon openng te tle\n");

Mwrite sAudet nformata to the fle


fpriutt (Alelointen,"Nane: s, stvdeut name );
fprintf ( fleloiten, "Rotrnben: dln sterd. rollNumben );
fpaidtt(kleloiter, " Manke! od,2f\n", shdeuct. mank);
Reatfscanfl0,
ing Datafgcts(),fromfreadl)
a fle:

-PSynt
uopoe clata forom opencd file

* int fs canf (fILE * Ale Pointen , cot chn tformat,)


" chai
*f3s (cln t , jnt n, fILE *flePojnten
-t tncad (void ptn, siz2e - t sizc ize-t nmcnt, fILE *filePointen))
fs cant ) ncad fomated
, fyct:() 9cads a ine of tent,
data
a fneadl) ncads a block of data.

Woutfprintt
ing Data(),
to q fle :
fputs (), fuwnitel ).
" fupose- To write data to an pencd fle.
" Syntax
"int fpnt f ( fILE *flefonder , cont chan tformat,J;
tpucs Cconst cha *st, FILE **lefointer );
" Si2e_t furte(cowt void *ptr, Gize-t size, Gi2e-t nnonb,
FILE *flefoite
fporintfl wnites toratked data , fput() wtes a
a block of data.
Moving within file:
fseek(), ewin0
Pupoe- o more te fle pointe to a tpe ci fie
the fle. Locatton wihn
t fsek (FILE *fefoden ,
" yoid Long offset ,t whcnce);
rewind (FILE *flefojvden
fseekl) llow andem accet
baed ow
lwhenee' by mog t a
reind() mmoes theCstut, cnet, on end of pecited poition
pojndes to the fle).
beginng of the fte.
Il clote te fle
fclore (fle Pointen);

fle fohde =fypen


fypen ("sthelect
l"stdent tnfo.4x+",

Sooor opeay the feln");


tf ("

/Read and olyolay the stvdert intorndian frem fle


printf ("n Stvdeict Intemton stored in tle:ln";
NULL) f
while (faets ( line, Sizeof (line), flefointor) =
pritt (s", ine );

fclore (leforntea );

3
pPrgam that eads a teot fle hd
Q8. Ceate
Cont the wbe of
#incltde <stelo. h>

# defne MAX_woRDLENhTH Go

FILE * fteloivden ;
lhr fleNane Cso];
clhan wod [MAy-wORD. LEN6THJ;
jvt wod Cotz0,
pivtt ( Enter he mame ot te file ");
Scantl s , ile Name))

file Poiten > fopen l fleNane. , "");


it (Alelinder == NULL)
pintt (" the fite.\n");

wile (fs Cant ( flefoinder"


wCAd Couut+t

fclove (fleloinden) Wbrdcot


prindf (" The tle s' cantus od wol. \n", fkName,

You might also like