You are on page 1of 50

ut

In man-machine, symbJas's~, it is ,man wbo must adjust: The' maohln,e.s can ;~I.

r - input/out ut Ilbn i, the big I,.t and m im - rtant - . tb, stan

library, A befit, il'- lofty s tarus we n devote an entir chspter

II he <:stdlOI " h>111e der.the -rimuf rep 'i", inpur/ou ut tun tions.

I', ~'ve been u ing <:stdio. h>i 1,_' I hs pter 1 and we have ex : rience ith th, printf~1 aoanf', put.chax .. get,C!har., pu: S, ,M gets funetin '" 'IIi eh pter provide n1re inf innau - D- b . -t hi ,a_I - si , fun J' jl' ns, _, Il asintmduein,~ a hi' ,0 '0 -, fun tin -, mo :_ of' 'hi h deal with 1"'11. ,. Form - a el moen' I, _ the

- ,

Dew fu.n_tinn" rule clos ],y r- Jared 10 run ti ,'D.L: '," alr - dy

acquaint d. fprintf f r in- lance is th , WI ,I, sion' I I b printf -1- r-

W "ll start the ehapter with a di u' '·,i - n ,f ,- "me b': sic I ssu s: th stream concept the FILE typ - input and outpu redireeti '0 and th di rer nc betv file md bim - Iles Section '2 1 } ,- ,- -, ll he n turn I~, -nncti ' ", ha __ '

pecific Ill" If! r 1 with files, in -ludin ,-~' functions thar open and cl ',: 1iI~' ,'e tmlon

ft -r covering printf .. acanf. d relate - fun ti-n. for inpullol1 . it I Se ti. m ' '2~: . e'Illook func ions that r ad ndwri I" n~, rms tt ed . am:

• getc putc, ,II nd related _ uncti . I '"~, whl b r d' "d WTi e _ n ~ " hara terata tim ~ I sec tin 22. -) .

• Ige:ts put s d related unctiom which read and wrlt 1i_[]l/iu2"13

( ection 2_. c-,).,

1_IICI_'tiOrL 22.7 then sh .c-_- i h I, to pe orm r' nd m n _ d ~ ;!

inall -ten,I,111 2 '.,8 describes th spri.nt.f snpI'intf and s,scanf Iunc-

tions, variant. ofprintf an ac arrf IhHl ~. ic [I . I" ring orr-ad from _ I-J ring,

Thi: chapter c 'fie', all ut ei t the function in <stdio".,h~. On, of It· ,~. ight the pe r'ro'r function i '- clo Iy related to [he <srrno .,h:;., b, ader, :'0

540 Chaptet 22 Input/Olutput

IoU-I lp n j - un il . ecti ' hi .h discus ~,_ .. rh . he er, _ectil:1 ~.'. I · 0 f. the remainins function i(v' P-I intf,~-p~ in ~ f, vsprint'f,., vsnprintf, vf,scanf 'vac~anf" and vBscanf)~ These functions rely on the va_l.ist typ , which i intro lu I d in that s ction .

• "'1 Ill' "9., n [' andard in- ut/output uncti ns bel n~ II' <st:di,o .. h», but, ncb

~wcha -~h~ head'er "35.5 n ,t th ~ case in "_.' here ,~_11' 1/10 I. n ~ti n" ali ". declar d in tho <wchar., h» hi" de r~ Th <wc~har Ii h» Iuncti ms deal with wide ch __ r, _ ter rath r than ordinary

characters: the " d nW~1 LI that m 0 thes functions closely re~ em . Itt: those of

e atdd.o . h», Functl n in <:SI' d i o 'S h>- tb~ ,I r adr writ" . 'am are kno n as ,6'" t ,IP,II,Ilol pu,I.(ul,' "hVIJ,",· similar functi n m <w,ch,ar'i h» at" called wide-charaet ilzp'utto'"tp".t function ~

Fll~ Pointers

1n "~ the term tream m. ans any source of input or any destin. t~ n f r output Many In' U pro trams like th on .' in p:ll,'~' iou chapter obtain all their input from one stream, U iually ax . crated ' . ith the teyboar ) and. writ all their output _

, ,. ther trei m (usually asso iated with the screen).

Larger program s may 11 red addition al streams, The: e ~ urearm I often repre ent

J 's stored on various me lia (such ,.: )' rd drr e' ~ COl., DVDs,.,,an flash memory) but th y could j u - a ea~ it be ~, 0.:[' te ith .' _' . ic I, hal 10'[ . t re Iles: netW,I.~_. port, print 't and the lik '. We"H concentrate n til, s.. inc' .they'recommon and easy t understand. (I may even oecasi nally 0: th terlnfil when Tshould

'ay stream.] Keep in mind h wever that many of the function' in <: S t.di o jI h> 'Ir equally W.: II with all stre un ;; not j ist 11,1' I. me that repres cnt file .

easing a str am ill ,a C rogrnm is dn through a file pointer which has type'

FILE * I(lh, FILE type L de lared in c s t d i.o , h» ',' tai I tre .ure epre-

sented by til P 'inl r; with t ndard name ';,we can die 1 ·r e _ ddltion _] file P int m a .needed. For xamnle if program need, two streams in addition to the tandard 00" ~I it might c main the following declaration:

A program ma- declare auy number of FILE * variables although opers ting systerns usually H- it 'the number of . tream .1 that can be oper ' t one time,

-c at.di.o . h> p_ ides thr I '1 andard l treams (Tahle 22. I )1. Thes '81n aI'l

ready to use=-w . d n t declar th: In" and ·W· don't open or close them,

i!T"~~lbl 1)'"1 1

J.'a.. . e ,JjoIj1'M..,

. tandar 1 Stream

22 1 Streams 541

'fdult .etUlillf:

~--

K' board

FiJ·· Pointerlr~"R'

--~--__..-

'9 ,tdiu,landaM'd input

at.dout; Standard .oLlt ut

s td,err Standard ern

Th Iunc ~ u that "I_-V' It,,l d in pr vi U'~ hapt r .. '-prin't,f~ scanf~ put.char. 'getcbar" put.e, and 'g.ets~ ,tJlain inpur rom stdin ._ td send eutput t stdouti B~ defuul ~ stdin r pre ents the -ybo"IT'd: stdout und atderr repre .. 'D'l the scree L HI wev r; "1 an' . p eratins syst ms alln ' these de Faull meanings . I be _ bal1~'ed - i. i m chnni ·,m kn ,. n 1\ redir« etiou.

T)1pic-~Jl.w CUD f ro a p~ - gr m to ( btain i' input rom ' ~ lle i n ~. ad 0 fr m lh ' keybo I~ by putting the name f lh~ fit 'I n the I'" mman I line, prec ded b th -c charaet or:

,

demo <in. dat;

Thi technique known 11':· inpui redirection .. essentially mak . the stdin str am repres m . fill (in .. dat~ in fLU ,c_ e insu a I ofthe keyboard, he beauty, redir~ xion j that th demo progr (11 d(JB"H t IL alize that if, rea log from in. dat.: . far as it "know '"'1 any , I, it) xain fronl s t din l . - ~ n:o entered: 1 lli" key board,

Olllpal,retiirecRolI L, similar; it dir - nn,g [he st,douttre~lm i usuall done by putting . , fill name on the c mmand I me. pre: re ded h the ~ char acter:

All: d 'hi ," rttt n to S'" dout; will no - in 0 til otrt . dat; fi]e in'~bl Jld of, ppearing on the-screen. In jd!e:nta]l~ w ~ can, c mbine output t d lreetion with in U[ redi ... rection:

The <_' nd ;:a charaet rs don't have to be djace nt to I I le nam .. all! th order in whi h the redire .te'd fil . are lis tied doesn't matter. so rh tollowina I. xampl Ytr, uld ork jut as well:

demo <: in, ~ dat > au - . dat; d~mo >cut.da cin.dat

- - -

" ne problem with output redir cti . n ~'" h L· -erythin, writn 111 L· s t.dou t j .

P'l1' into a file, If til program aoes off th rails and be. ins 'ritiJ1'PJ error message '., we won l,e, them until we 10k at the file, This i, wh· -,. _' etderr come in, B riting error me: '.~ g . l stde,rr ins lead of st.dout.. we can 'tFUIBraJ1Jtee [hat tbOL .rnes ~I' ore. '.' ill a ' IP _ ar 00 the I Icr:_ . n even W h :-]1 SI tdou t ha belen r direc ted, (Operating s sterns , ften ill w lstderr Itself t ,be r directed, though.)

<,stdio ~ h.> uppons two I u1dL offiles: text and binary. h. yies in 3 text jil:e r ipre ent characters, making '~l possible for 0 human to examine the' 61 or edit 'it

The I\OurC€ code for a C program i tored in a re tr fll '" for example. In ,3 b,rRaryl

file', on the other han,d~yte,. don't ne e ISIJ"iIy r presen '. hara t rs: groups lor byte might represent ether types-of data, such as integers land Ioa ',- g-point nUJDbers, An executable C program is.stored in a binary file, a you'Il quickly realize if you try to look at the contents of one,

Text file: have two characteristics that binary files don't posses

• Text /11£'11 are divided ,i,rto ,'iDIBS~, ·'ach line in ,3 text 11e normally end wi one or two special characters: the choice of characters depend' 0' tb ~, operaring system, n Window s, the' end-of-line marker is a carriage ... return character (,I \xOd I) followed immedtare~y b:y ,iJ line-feed charact ~r (II \xlOa I). In UN X and newer . ',ef J.OIfl~ of I be lacintosh operating system r(M sc OS)I~ l.h end-of-line marker i I~ single nne-feed character .. Older vers ions of Ma OS u a . ing[e carriage-n turn _ haraeter,

Textfiles IR'Q .. ~ ,cuRtaiN a rple:clal' -'lffld .... af1ile' m'a:rker., some opera ing terns allow a special byte ro be' u . led as a marker at the lend a te . t file, In Window· 'fl the marker i··. ,I \xla i ( trl-Z), There's no requirement Ih,211 Ctrl-Z be present, but if itt is it mark: the end of the ~il ~, any bytes afterCtrl-Z ar to be ignored .. The CtrJ-Z conventlon is a h ldove - from DOS~ which in tum inberired it fro'm'lM, an early 10' erati ng s,yslreml for . ersonal computers, MIDS'l other r- perating i" y " tems, in -lading UN, - ~ have no special end-of-file character,

Binary file aren't divided into lines. tn 3. b'inary file, there ar-e DO end .. of-line or end-of-file markers; all bytes ar treated equally,

'Wbe~n 'we wri te data [, a fi le we' 11 need 101 IC'OI1Silder whether to' .... tore it in teo t 'ann or ill binary form, To, see the d'j ference, c nsider h10,\'1 we might tore tile number 3,21'61 in a, fil ','0 e option 'w,ould be to 'write the number in text form as the ch ,I Deter, 3 21 7 ~ 6 I and 7" If th .. bars 'ler 'set is A slcrr~, we' d have the fo UIDW'ing five .. ytes:

100110011 00110"rllLo, ueu.i mra COllOl~O 00110111

, 6 J

r 7"

The other option is to lor . lh' Dumber in biuary"wbicb would take as few ,81 , 0

bytes:

[ 01111111 1111111].11

HMI~endi9~ arder )10>20.3 (The bytes will b . re ers ed on sy tern" that "lore data In Iittle-endian order.) . -' .'. th.i. example . ho,toring number in binary CRn often ave quite ICJJ bit of space.

When we're writing (1_ program lb,'t feud' frl', m a file or writes to II. file, we need to tak into account w: - Iclb r if .... a text IDle or a binar- file. A program that dis .. plays the contents of a file 100 the creen will probably assume it's a "ext ~le. A file-

I opying program on the o:tblef hand can't ssume hat th file tn be copie i :a 'text file. If [I dl >~ '.' ,- binary ", es - ontaining an end, ... of ... fil!" char ctlef won't be Icnpi - d L'- mpletely, - 'hen W can't 'BY ~.. sure whether a til. '1 tel OJ bin I _I itt safer to

IS ,ume th . .t it I bim I' •

fopen

r'8stric keyWoMl ... '7B

ICD

1.\. rill

Sim Ji -~t is .. ' ne f the a tr-action,' innu end I input redirecti n; there '. L1O' nee - to . ' en a file, clos: I f1 ,If perfn m aB'_th~ r explicit fll operJ tlons, Unfortu-

nately redirectionis to limi __ d or Im_ n_, ap ilicati 'H-'~ aen a prl gram reli .',

redirectiou, it bn no ,O'D 01 0 er its ,file. : it d .' sn't I. _', en kn iW' their n -- ",~ Wir-e , till redirection doesn t help i - 'the program needs to read fr " t 0 files or writ '~.I two' ,rul - at the i iame time.

Whe n n:t tlrection isn 't ~ nough we'Il end up using the' file op ration that

cat.d.i.o _ h~ pr vides, In tbi I' ti D C 'll explore these opera i 0 .--,ttich

'.' ] de . ""1 I·' "'iii...... b · til fi-I '.' . d I . '.

Inc uc .' OP'-'ntnC!lIi! 11_'- c I ',~ In!" a rue C ranging ~, w: -, ',- .1·,1 :U' iere II eung ,at

~ ile and renaming file.

0·.. il_*'_. ~

, .. up.nlnga

FlEE ~. fopen (const; char * rlBst _" ct ilename, eons t chaz' restr' ct: mode) ,;

Openin a file for use as 8 " tream [1'eqUU"I' all _ the f 'OP len. function, t open I

nrst argume nt 1'" a s ling I.' out "11m, tile name o. the file t -' b - open d. I .' ~ tile n me' may in hid _ informa 'on _ b ur tt e '~"'II" i ea ~OD ., U eh a .', ri CJ pe ill

or path. T, e: ~Co.l1dargum 'fit j .. ' a 'mode ,,' ring tl at sp .~ .1_'" . b ' r a,p,' I .

int nd t perform on th - ffi le The triIlg Urn fOT in tance, indi - 'e. 'S that da _ _ '. ill be r ad fir m the file. but none ". iU be written to it

_ .. ore that res'trl.lC app.at twi 'e in th . prototype for th ' fopen fun lion. restri,et . bleb i·- a C ke word indicater hal filename, md mode should

point to trim I· that don" __ ar~' mle,mo_ 10, arion -"" he 8, pr, " '.' _ . pc-or f open

d :- . n't e main restr'ilct but is . th rwi e Identical, res'tric,l 113 I noe _- "Ieel on the b havk r 'of fop,en~ ,0 ~ _ an U I· U- ju ~ t t 1_ nor d. In this, and sub equ nt chapters, I U italicize r-estrilct 3' , remind r hat if .' I 'C99l ature ..

'Indo I pro ramrn r : Be '. ar ful whn h file Dam' in. I~ call I fopen include

the \. chara ter~ sinceC ---, 'at \ I.' Ute I 'an escape s I'qu DC-I. Tlu . all

fopen ( II C : \proj ec, \ t,es' 1- dat II I III __ II')

,ill fail. -I '~··11. ,- the comoiler '. rea, \t a a chara -ter ap . ,\p is .,: a alid

, haracter e c pc but 10 1 _. like on ., Tbe -.. an ], Lr l state that i me- ning ~,

hi ~,

Tab'I,8J "2- -'1

L.1~.iIiiI! ill~

Mode Strmgs tor Text nes

undefined.) There are tw ways [0 avoid the problem, One I', [0 118 \ \ iOl lead 0 \:

f op~ ( II~ C' :: \ \p'roj'ec t \ '\ tie: sot 1 .' da t ~ I ~ ~I' r II )

TIle other 'technique i.~, even easiler-jus'[ use the' /lchnr,a,c:tl::'I instead of \: fO,pen ( !Ii,c,: lproj set: /tes:tl. da't II I' II r~'~ )

fopen returns it file pointer that the program can (and usually will) ave In ' variable and u ~H.~ later \\fh 'n, ever t~ nleed~ '[0 per: orrn an operation on the fi le, _ ere' a LypieaJ 1[;311' IQI ,fopen,wh:ere fJMI]s a variable of type FIL,E' '*:

1* opens in" d,at for reading .. I

Whenthe program ICaU' an input function to read from .i.n. da.t 1 ater , it will tuppI,)! fp us ,an argument

When i'l ran't . 'pen a file, £oplsn re turn , I :,1 nul] pointer, Perhaps the file doesn't exist, or it' s .in the 'WJOllg place, or we don't 1l:&V1f!' penni F;:i" n [10, open It,

Never assume that '~ file' can be' opened: always test the return value off operr to make sure it's not a DuH pointer;

Mode:s

Which mode string we'Il pass tc f'open depends [lot only 'On what operatiom we plan, (0 perform 0:0 the file later but also on whether the file contain' text orbinary data. To 'Open a text file, we d use one of 'the .raode trings in Table 22.2,.

II r II Open for readl Dig

II W U Open for writi ng (fille 'need not ex i '~·)I

II a II Open for appending (Iile need Dot eais Ji

II r+ II Open far reading WId writing, ,star~i~1,g ,at beg,iLtm~flg

IIW~ II IOpen fen' reading and writing (truncate if fl~e ,ex'j '[SI)

II a+ II Open for reading ,anu writing {append if file ex]sts)

__ ~ _~_~ __ ------.J

When 'we use f open 11Ji open a. binary 'file, we 'U need to include the letter b, in the mode string, Table 22.3 lists mode string for binary file .

FrO')D Tables 22.2. and ~~.3., W'C sJee thal ,<~,tdio 0, h>, distinguishes between 1,'{ riting data and appending; data When data is, written 'to a file, it normally overwrite < what was, previously there. When ,I file is opened for appending" however, data written to the file is added at tile' end, thu preserving the file~-~ original contents,

By the way special rule' apply when a file i opened for both reading and writing (the mode string contains the + character). We can 't switch from reading '[01 writ",

'Tabh.~ ll~Ji Mod Srri ngs for Binary Files

Open fnr reading

Open for writing (,~j'~e need not exrn~,t) Open for ~ppendin,g (IDe Deed 0101 e}list)

Open for reading SInd writing" starting .ill begimung Open for I~adj ng and wri ling (truncate if Ii le exists] Open IDo'r readi ng and \wrhing (append 'i f rHa :eKis~s )1

----------~---------

II rb," IIwbll !labll

ii r+D 1'"' or ~~ rh+ II II~ w+b Ir!' o,r I~~ wb+ II

I'I a+b II' or ~[ah+ II

fi1Ei",p{)sit~il;l1 ingifuflc~i(),flS )I- 22~ 7 i ng wi thou t firs tea] J i ng a 11 1 e-p 081 tionin g fu 'Dcti'OI]1 unle .co i .'. the reading opera tion encountered the' lend of the' file. Also, we can' t switch irornwrjting to reading witb,out either calling ff 1 ush (covered later in this section) or calling ,8. file-positiouing function,

int f c l oae (FILE .streamJ ,;

fc:h]se' The f cLoae function allows a program ttl close a file that if D10' longer using, The argument [0 f c los e must be' I! file' point -I" obtained from a call of f op en or freop'e,n (discussed later in this section}. f,close returns zero if the file' was closed successfully; otherwise, it returns the error code EOF' (a. macro defined in

&1" i('st,dio ~"h»~,

'To show how fopen and. f clas,e_ are used in practice, here's the outline of a

program that opens the file examp 1 e '" da.t for reading, cheeks that it wa opened snecessfu ~ Iy,~, then closes it be forte termi nating:

# Lnc'Lude <:s,tdio ,. h:> #include ~stdlib.h~

*de~fine FILE NAME ""e"xam,ple. d .. iltlll

Lnt; main ( vo.i d,j

{

fp :; f open (F I L,E N'ANE I 'IIII r ~~') ;' if (fp =~ NULL) {

pr int f { ~~ Can I ,t open ~ks \n'u J FILE NN4iJ:} ;

-

ex.i t (EXIT F'AILURB) :

}

.fC10:E,'H (:fp) ; return 0,;

}

IOf COUT,se~ C'programmers being the 'way they are if's not unusual to see the call of f opem combined with the declaration nf fp:

FTLE, *fp '= fope:n (FILE_NAME, urll);

C'h'B'P" te« 2--:'fj'

I .'. '., .'. yol ',€"

Dr the test against NULL,:

if (fp'·~ jf:'ope·n (PILE_NAME" "r'l~ l) :=:= NULL) ' ...

FILE *freopen (canst e,har l' ~."es·t.r.ict .f t len,arne, canst ohaf * «eetx'iet: mode, FILE ~ xeecr.ict: stxleam);

ire 0- -p e '-n-

-I-';_'; •• ,·'1-"":' '

I. '-. '.' .... , I

freopen attaches ,EI different file tal a stream "that, . already open, TIle most cornmon use off reopen is to 21:S1'_ ociate a file with .ODf:' of tbe standard streams (st di.n, etdo'u.t or Bt~derr). To cnusle a program to, begin writing to. the file foo, forinstance, we could use the following cal] of fr eopen:

i:f (, f r·e,olpe·n ( il'lf 00 ~I' {I ,~ W til, 5 t.douc l ~""""' NULL,} ~

I * error; 'rlOlO Clan ~ t bile opened .. I

}

After closing any file previously associated with s'tdou"t I(by command-line redirection or a previous clan of freo'penl-, fre'open will open f'eo and associate it with at.dout..

- - -

fre,o'p,en;s normal return 'value is its third argument (a file pointer), Ifit em) t open the new file, fra'op,en returns a null pointer, (freopen ignores the 'error if the oid filecan't be elosed.j

I'. IC991 adds. ,8 new twist IT filename is a Dull, pointer, freopen attempts tUI change the stream s mode to that specified by the mode parameter, Implement-a .... lions. aren't required to support this feature, however; if tbey dO'~1 they 'may place restrictions on which mode changes are permitted,

O'btainlng File Names 'from t e Command Line

'When we 'lie writing a program that will need to open M~ file one problem soon becomes apparent: how do WIt;: snppJ,y the file name to the pJ"crgram'7 Building file names into the program itself doesn't provide much flexibility and prompting the user 'to enter file names lean be awk\voJd .. Ofren the blest olution is to have rhe program obtain BIe names from the command line. When we execute a program

named demo", for example 'Wit m'igbl upply it will'll file names by putting them an

- - -

the command line:

In Section 11.,7- 'we SI'V how to access command-line arguments, IlJy defining main as a function with two parameters:

int ma.i.n (Lnt; arge !~. che r lk argv [] )

{

,a,rgc is the number If command-line argumen s: argv i. D I. 3: o P in 1-"1 tl .; argumen rrinas, argv [IOJ lJ ' the program name, a,rgv [lJ tblilugh argv [,a,rglc-l] point to the r rn inin ,ar,6umenl:." and argv [a.rgc'] i a Dull pointer, In the example above argc i I. _ ..... azqv rO] points to' I trin ~ co nai ~, . :_~ tb program name largv [1.] point, tQ th . tring U names .' da't II'm Ii nd ,a'r'gY [2] point te the string udates",datu:,

argv

1

_
-programl name

,
I .. n a 1[1 e El d PI 1 \0 I
I .
I
,d a: -t- e s a t \0
,.,
V 3

Tbe following program d . t ,~ -1m n. ~~-. i _ 3 fill exis and. an be II' . n 'd for re din, - ~

When the program is run, the ue' . it a fiJ own . :

canopen file

The' program will then plrinC eitber fillt can be. opened .lille can ~ t he opened .. I " " user enter I the ' _. l[Jng numberof argume'Dt· on the command Iine the program wiH print tho m oil a e uaaqe.: canopen fil,ena,me tn remin the

u·er that c~anop@n requ 'Il.· _. a, I . in ... 1_ _ 'II~ ni- .

#includle <s'tdilo. h> #includ~ <stdlib.h>

int main (int argc, char *,arg'V' [] )

{

FILE *fpl ..

tf

if (argc ~~ 2') {

printf (rlus:agB:: canopen filename\,lnll) ; exit (EXI'T_FAILUREl ,

}

if (,tfp' = fopen(argv[l] ~ IIrl») -- NULL) { prin'tf (~nt,s clan II t be o!ened\nllll, aiagy [1.] )t ;" exit. I{EXIT FAILURE:) ;

....,_ _

}

pr Lnt.f (' If %,s can be opene'd\n1lll Ir argv [1] ') i f c Loae (fp) I;

return 0;

}

Note that we can use redirection to discard the output of canopen and simply test the status VlUUC it return' I.

FILE -,t·tmpfile (V'a_id), :

e har; *- tmpnam I( char Jt s) ;'

Real-world programs often need 'to create temporary files=-files that exi· t only 3< long as the program ~I' running, C compilers, for inS'Ut11Ce~, often create temporary files, A compiler might first translate a C program to some Intermediate form wh-ich H stores in a file. The. compiler would lhen read Ute file later a~ jt translater theprogram to object code", IQUC'-. the program is completely compUed-,tbere!ls no need to preserve "tile rue containing the program interm male form. -c S tdiol ,. h.>' provide's two functions, tmpf ileilnd t.mpnam, for working witb temporary files.

t.mlpfill'B tmpfile creates a temporary file (opened in f~wb+ I~I motile) that 'will exist

until it' .. closed or the program ends, I '. can of tmpfile return I a [de pointer that

can be used tel access th.le· file later:

tempptr = t'mpfile (.) ;

If it falls, 110 create a file, t mp f i 1 e returm I a [I uB pointer,

Ahh ugh tmpfile -is ea y to use, il has a xmple 10[" drawback .. I:' It I) we don't know the name of the file thut tmpfile creates, and (2) we can"( dlecide later 'to make the file permanent. ~f these restrictions tum out to be 3 problem, the alterna ... live i.. to create a ternporary file using f cpen, lor course, we don't 'Wiant this file to have tbe , ame name as, a previously exi: ling file; S WIC need some way '[0 generate D,f!W 6]e names" that's where the t.mpnarn function come in,

trnpnam t'mpnam generates a name for a temporary file, If its argument is a null

pointer", t.mpnam 'tOf'CS the file name in a static variable and return I it pointer to it

c:ha:r 'I< fi lename_i

f i Lename = ttn]pnam (NULL) ;'

Otherwise, t.mpriam copies the file ItaJl1~ into a character array pro,vided by the programmer:

tmpnam ffilename) ;'

111 thle latter case tmpnam also returns a pointer to the fir1t character ofthis array, L~tmpn,am L-, a macrn in -cat.d l.o . h> thaI specific hew long to make a character ana,y that 'will ho.ld ,3 temporary file name.

Be sure Ilhat trnpna'm-' argument points to an array of at least L trnpnam charac-

- -

ters. Al 0 be careful ~lot to cal' tmpnam too often: the TMP'~:MAX macro (defined

in _<frtdia;o h~) specifies the maximum number of' temporary file names that can potentially be: generated by t.mpnam during the C'X1e cuti 0,111 or til program, lf it fails to generate fl file name, tmpn.am returns a null pointer;

intfflush (FI.LE "',stream);'

veid aet.huf (FILE * l-estri·ct sueam, ehaz *' reetzs ict: buf) ; int .setvbuf (FILE '* restrict stream, char * restrict buf, int mode, si~e_t size);

Transferring data 'to Of' from 3 disk drive I at relatively slow eperarionAs a result, ir Isn't fea ible fOlf a program '[0 3C)CeS,S,R disk file' directly each time it wants [10 read or write a byte. The ' ecret to achieving acceptable performance is ,b"lfeTi'nlI~~ data written [0 8 tram is .DCLuaJJy tored in a buffer urea in memory; when it ~. full (or the stream i closedjv the buffer is "flushed" (written [101 the actual our-put device), Input stream: _I can be buffered In 13 similar 'Nay:: the hu fer contains data from the input device: input i read. from 'hi buffer instead of" the device itself, Buffering can result in enormous gains if] efficiency since oo'aeLi"Rg a byte from a 'buffer lor' .toting ,L byte in a buffer takes hardlyany time atall .. Of COUDH:~,~ It takes 'ti me "£0 transfer the buffer contents to or from disk, bu one large "block mOVIE!'~ is much faster than many tiny "byte' moves.

The functions j.n. -c S tdi ,01 " h» perform buffering automatic'aUy when it. seems edvantageou .. ~'I])e buffering takes place behind the scenes, and we usually dOD t worry about it, IOn rare occasions, though, We may need 1[101 take a more active role .. If sn, we can use the functions .if Luah. Bstbuf and se'tvbuf~

ffh.Jsh Wbell a program writes output to a file, tb,e data normallygoes into a buffer

first.The buffer is flushed automatically when It's mil or the file j8 cia led". By calling f fLuah, however, a program cam flush Iii file's buffer as of ten as it wishes, The calt

fflu,sh (fp) ;

f:flush (NULld ;

,* flushes all buffe~s *'

flushes all output streams .. fflush .retnrns zero if It's successful and :E·OF if an eflior occur ' .. ~

s'etvbuf

netrvbuf -ll'w' U .... h 1, e

" ize and lo ati on f '. e I ouff f.. '. hc' f unc in'. kind of bufferin de. ired! !; hi uJd be on of th

I e· ,1 is lru~ ered an . t c mtrol th thin "urn·fit.·, hieh spe i - _~ ILb, fnllnwin m era ... :

• _I;IOFBF (full buffering) Data ic £" ad rom the stream when 'he b

emp " writt n to tIl ,tr am 'h _ n it full.

• IOLSF Iine buff 'ng,.Omai read TI ihe.stre In if vritt ntc h tream O'De lin at a time,

• I'ONBF! n

lire tly

AU three DJ' .rn ' e defin ]11 <st:di!o, .. h~.) I'UU buffering i lh If

"U' am that aren t connected 10 interactiv _' device ..

ae t vbuf 's seccud rgume:nt (if it . 11 t a Dull point ~r is the addre f th

d - ired buff r, fie buffe r ~gbt bat sta i ' . tora '_ dur lin au nm j

durati '" ' e er b alloc .1~·' n ,~-,akin ,h-· I ," ~lIJ om ti · low', 1

. ee to be reclaimed autom tieallv u bl I .k exi · allo _'atin, ~l dynami any . nables 'W to freethe buffer when j ,"I no long r 1]1_ eded, 'setvbuf ' ~r; J argument OJ. til

numb r of by ! "! in ih ". u lug er buffer nl,I.· ~i b tter .- ... ,dj' rmancc: ._

smaller buffer sa ~~p I '.

For e . rnple, h t "li"IDb"an setvh1:lf chan the ! utf ringf

stre.·arn t- full buffering, U in the N b 'te in the buffer array as tho bu er:

IIQFBF,

..

- ,

char buf fer [N] ,;

.1'.\ ~

aet.vbuf mu t be called aft r at.ream .. (' pened but Ie'·· re any oth, r operations ar - p. rformed on it

11"1 also 19aJ to call aet.vbuf "lith. null pointer a the s n araument. whileh request that setvbu create a bu er with the specified 'j e. B'etvbuf returns zer,o i .. it's ·,uo e .. \it l return!' ~ n· u ero ., tlu - if [he mode ar,gu . _ ' t ,! - in a[ ~ d or the r' que' l can t be h' n )rc _,

setbuf setbuf is an older fun tj n t :1 ssumes def ull values fnr the buffering

mode and buffer I ize i' If' bu f i: !I null pe in t r~, the call s e t.bu f (s ,t ream i! hU.f·) i· equi alent to

!(vo:Ltd) ,setvbuf (stream, NULL,~ r-ONBF, 0);

-

. h '"I ' BUFS,IZ i a macro de ined in <8 dio .. h» .. TI " sethU£ ' UIl'_ tion is c nsidered obsolete: it not recomm ad d for IU~, in nC\1iJ pCII:. ra . s,

When. using ,s"et-vb,uf or s'Btbuf~ be sure toclose the stream before its buffer is deallo cared, In particular, if the but "er is local to a fu notion and has automatic storage duration, be sure 11(11 close the stream before the Iunctirm return .

Miscellaneous F'it! Operation

int remov,e (COll,st char *filenama) i

int renam,e (canst, char *old canst ch.ar 'ne'w);

The function: z'emove ,311d rename allow a program [0 perform ba -Ie file management operations. Unlike most other functions in 'his section, remove and r:en,amew'ork with file names instead of nitt!, pointers. Both unctlons return zero if they succeed and a nonzero value if they fail,

remove r.emove deletes a file:

If' a program IU' es f open (instead of t.mp'fil,e) to create a ternpcrury file i:t lean 11~C re;'mo,ve ,to delete the file before '[be program term i nate ., Be. mre that the file to be removed has been c losed: the effect of removing a file that' 8, currently pen 'i i mp lementati on-defined,

rename rename changes the name of u file:

r'enaue is b,mndy ~D[ renaming a temporary tile' created using f.open if 3 program hould decide to make it permanent, [f a file with the' new name already 'exists" the effect is implemeruation-defised.

[f the' fileto be renamed is open, be sure to close it before calling renanle.: [he tu nction may fai I if asked .'~O rename an open fil, ' .

. 22.,3

In this section, we U examine library functions that use formals,trin,gs to control reading and writing", Thes ' function ' which include our old friends printf and. acanf. have the ability to convert data frOJD character form '~O numeric form, during inputand from numeric form 1.0 character form during . ULPUL No" -' of the other UO functions can do such conversi ons.

. .tput

int fprint£ (EILE '* res'tri,ct strea'm,

canst ehar • restrict fo~mat, ; nt print£" (conat char '* :res'tri~t forma.t. j

The fprin,t.f and 'plrintf functions write ,3 .-ari;;1.bl number of data i'Lem~ '_0 an output stream usin,g a format string La control the appearance IOf the output The prototypes for both functions end with the' ~ ~ " symbol (an ,(d,/liplis).!, which indicates a variable number of additional arguments, Both functions return the number of characters written: 13 negative return value indica JI that an error o ee urred.

Tille D]]~Y difference between pr Lnt.f and fpr Lnr.f is that pz i.nt f alw,ay,s writes to 's,tdout (the standard output trearn), whereas fprin,t,:[ writes to the stream i ndicated by its fir t argument:

p,rintf I' '!'iTot,al: td\l'lll ~ total)'; fpri'nt.'f ,( fp, ~~T'ot,a.l:: %d\,n~'~, total) ~

1* writes to stdout ./ /*writI9S to f p '*/

A call of prin,tf isequtvalent to a co]) of fprintf with, etda,ut as the ,fu,t argument,

Don't think of fprintf asmerely a function tha writes data ''0 disk files, though Like n1.W1y functions in ,c,stdio . h», fprintfworks, fine with an.y outpllt stream, - 1 fact, one of the most CQ',lDmOl1! uses lOf fpr'int,f-,writillg en-or messages to at.de.rz the' ·'t£1lndw~ error tream-ba nothing todo with. disk file !. Here's 'what such a call might Iook like':

Writing the message to stde'rr guarantee. that it 'wiU appc,i.t[ onthe screen even if the user redirects 53 t.dou t.,

There arf!' two other functions in ,<st_die . h» that can write formatted output v" .. printf functions .~.,1 to a stream, hese functions, named vfprin.tf and vpri,ntf are fairly obscure. Both rely on the va_.lis,t. type, 'which is declared in <std,arg!, h», S,Q they're discussed along with that header,

u, .. p,rin,'tf ICo'uve:rs:ion Specifica'~ions

Both p.r i.nt.f and fp,rint,f require a format suing containing ordinary charae .. tiers and/or conversion specifications, IOrdluary characters are printed a· is; CO'lIV'er ... , sion specifications describe how 'the- remaining arguments are [0 b converted to character' form for display. Section 3.1 d iscribed conversion specificatiorrs briefly. and we added more derail' m later chapters, We'U now review 'what we know about conversion speci fication "~ and En I in the remaining gap" "

A ... .pz'Lrrt f conversion specification consisn of the % character, followed by as many as five distinct items:

Table 22 .. 4 -FJ,a~~r for ",t~plrintf Functions,

21ti") ~I ~ilUJ

g. JJ. 0', .·,1 o tt

f

min~mum

file lid width

Ilengt:t1 mo~Hfme!lr

Here's a detailed description nf these items .. which must appear in the order shown: .1 Flags (optional; more than one permitted), be - flag cau: es ~ert justification within a field: the other flags affect the W~ly numbers are displayed" Tablc22,.,4 gives a complete list e,f flags,

Ping Mf!,O'D'jfllJ

----------------------------~--~

Left-justify within 'field. (The defauh ts li,ghljU alfication . .J

1-====== -----------~--------~.

+ Numbers produced b)i .. i,gored eonversions ClthV,3),, begin with + or -. lNonn,aUl'"

OD~Y negative numbers are preceded by a sign.)

space Nonnegative numbers produced by signed conversiens ar-e preceded by ,a space, (The « -aug overrides the ~f/;}ll(~'e flag,.)

# Octal numbers begin with O,~ nonzero bexadecimal numbers with Ox or lOX.

FI,oa~in,g-point numbers always have a decimal poim, Trall h~g zeros Mien t removed from numbers prh1'b~d with tbe g lor G conversions,

o Numben are padded with leading zeros up [0' the fi,eld \\Vidtb,;e The 0 flag is

f zero] ignored mf the IJflnv,e-rsionis d., i. D. U·T ,x nrx and i;I precision ; s specified. [The - lla,g overri des the 0 f],~g.)

II Milli"'~'fl' ... fi'e1il u~idth (optional), An item 1I,all" s too small to occupy thi number of character 9li;U be padded, (By default, spaces are added to the left of the item thu right .. justifying it within rile field.) An item thar' [010 Iarge for the field width \Will till be displayed in its entirety, The field width is either an integer or the character *., J fw is present, the field width is obtained from the next argument, If this argument is, negative .. it's treated 8'.- a positive number

~ - -

preceded by a - flag ..

• Pre,ci,lOl' (optional), The meaning of the precision depends 0-0 [be conversion:

,d~ i, IO~ U .. x .. x,: miutmum number of digits

(leading zeros are added if the number bas fe\~ f!t digits)

a" A. @'. E .. f , F': number of digh allier the decimal point

g, r;: number uf significant digi ts

s: maximum number of bytes

'The precision is a period ( ~ ) followed by an integer or' the character *. If "It' is present, the precision is, obtained from [he OX! argument, (U this argument is negative the e lfect is the same as not specifying IiI precision.) If only the period j s present, the prec is jon is zero,

554 Ch~pter 221 Inp,ut/O'utput

I. h j h odifiers for .... print.! Functions

h\. ~

u'lrgtIJ' ,'no',difi~r (optional), The presence of ~ lenath rna lifi r indicates. that the item .[:0 be di "p[a.yed has at ty P that 's longer or ~ hort _ r than i. normal for n particular conver ion specification, (For exarnpl %d normally refers V I an int alue; %hd'i [1* I', IL' display a ahort; int · nd % ld i - used t ill, p~a,~ a. long int.) Ta 'J , __ .,jl lis each length m-H11'T~ the con ersion specifier with which it may be ,', 'ti, and the t, pe indicated by the combination of th two, (Any combination 0" length modifier and conversion specifier not hown 'in the rable causes unde fined be havior )

Len'gllh'
,odifl Conversion ptcifi.Crg , 'eoieg
F i ,

hh" Id i., o~ u, x .X signed char~ Wlsigned. char
n sA:gned char
h d, ; X short Lnt., unsigned s'hart .int
1,. o, U, x,
n short int 'If
1 d. , X, 1· .. · t una i,sned long int
1. o U 'X
'II ,L-_L.IIi. '_ III on,g- .li rr .
(ell) -
n long int *'
c wint t
-
s wcha.r t -I:
- "
a, A~ e, ]Sill f" F~ g", G no effect
,1- i. 10019 into unsigned
11'1 d. 'OJ u, X X long Lonq long' inl:
(ell~eU .
n LonqLonq tnt *
. .L L, o. U.,X, X int'm.ax
J d, t~ uintmax t ~
- ..........
n i, :nax t '"
-
t d· f U x, X size t
z ~- 0,
- ~
-
.' t. ..
n S1.ze
~
-
'C t d 1. o~ U X X ptr·diff=t
n ptrdiff~t ~
L, a Ai e, E £ F 9 G long dounl.e
• • Con'l,erS-;O'R'rp:£t:ijieT@ Th .cenv r in pecifie. DIU ,"t be on" . f the eharac I n listed in ~~ - le 22JJ. <', tlce that f, F, e, E~ 'g G a I and A are an designed to writ dcuhLe values. H,.~ ever th 'y work. fin with flo'at value as well: thank, to the default tu, ument prometiens. float argument,'! are converted automatically to double when pa ," to' a function with a variable numberof ,afgrnD,en ' . Sim ilarl , , I hats '1Le, p _ . ed tc .~~plr int f is ICOnv rte d . ,ll 1.IJnat [; eaU· to Lrrt., s', the C Icon' ersion won .. proper) "

Be carefut '. f illow lh rule descri ed h . r :; the eff . ci ·f u .ing an invalic converI ion pe ifi ;ati .. ITtl is u nd ~' fi ne ..

~- b';I.rIo1 ']I'" _ hi

IiI. _~ .~~I ','

Conversion S, pee ifiers fo r' .,",prin't~f Functions

CO:ll~1'{lr~'iaJI S,ec iji,B"

,

earnug

a U",X'I'.X

Converts. an uns~gned int value fO base 8, (e), base ~U (u), or base '~Ij 1 I[X. X). x displays Lhe hexadecimal digH~ a.~f Ul ~nwer case: X displays

them in [IJP'P~'f case, I

.a.

f Fo •

. Ii r

onverts fm double value to decima! form, putLm,g the decimal point 10 I U1t~ (~unECl PIl:l$~ljU[l. lf no pn!e.nsio_o rs specified, displays ix digits after

U11C decimal point;

- - - -- c_=

Converts, a double value to scientific ,Do'LaUUD., U' ov precision is speci-

fied.displeys six digh~~ after the deeirnal poi nl~ ]f e it 'cho" en, (h~ E'xpn .. nent is preceded by thE letter e~ if E is chosen, the exponenl 'is p:re,t:edeti hy E.

g convens adouhl e value run either' I"orm or e form. e form j', selected I if~~e number's eXjlufi,ent is less ~luul:l ,-=I. or' greaLer than or e~U'al to tbe precision, TraUirtg zeros are not displayed (unless the # flag i's user] ';, ,m' decimal [1(lhl1t appears only when rQII~ow'ed by n digit. Gcho(llses between

F and E forms.

Converts a double value '(U hesadeclmal sc i,enlilic llJo[,atiuI][ using the j

form [ -1 C,xA ,. h""1~1p,±cl" where I-I is an optional minus sign. lhle lI"'s re,preseru b~'x ill,git:S., ± is either a plus or minns sign, and d is the exponent, d

is 3 decimal number tbalreprrfeslCrt'lJ1i II power of 2. IT DIJI preeision hi, speeified, E:f1mlSh d'~'gi;U ,W"~ w,spla.yed after the decimal peint torepresent the exact value of [he number or possible). a disp~a'ys [be hex (Hgmu; a~f U]

lower case: A display!) them in upper Cil5C .. The choice of a or A also 8ffecL~ the case of the letters X 'Iud p"

B

'~riU!!5 the characters P():inb:~d to by the argument, S,'.OPS writing when tb~ ~ number of b)1e& speel ired Ill) [hie precision 01' presentj 1~ reached or anull character is, encountered.

p

Converts a voi'd \It value Ito printable form .. ,

The correspu~uli,r~g argument nUJJd point to an u~j"Gl of type i.nt. Stores in, this objec't lhe Dumber ot characters wriuen so far by [his call of

... printe; produces no output.

n

The conversion specifications for pz Lnt.f and f,print r have' undergone a BInDber of changes in. IC99:

•• A,cld:ftio,l;"€llle,rKtll' "'I(),difi's'·'~ IC'9'9 adds the hh, l1!i j, z, and t length modifilent hnand 11 provide addj l iona ~ lengih option ! j allows grearesi-widsb i ruegers to be wri UeD ~ and z and t m ce it ea ier to write values of type s i, ze~t rind pit. rdif' f_t res.pecti.ve~ y.

5561 Chapter 22 lnpu,t}O'u,tpul

Tabile 221 .. 7 Effect of' Flags on the td C nversion

~ Additio"'rll' Co',I1J'ersio,n sp'e,ci/i,etlf! C9'9' add" the ,F, a, and A conver ion specifiers, F i,!t the same as f except for the way in which infinity 2Ul(] N'~N (see below) are written, The a land A, conversion specificationsarc rarely used, They're related to hexadecimal A'ioaling constnn :S~, which m~ discussed in [be Q&A section atthe end of Chapter 7, .

• _ 'c __ Itty to write l"Iji,I,li') IIJlll ,NCiNjj The IEEE 754 floating-point 'standard allows the result of a floating-poi nt operation to be infiniry, negativ iLlfinirty. 10'1" NaN ( ':nOI[ a number"). For example, dividing 1 CiO by 0.0 yleJds positive infinity, dividing -1.0 l Y 0.0 yields negative i nf Ifilhynnod di- iding O~O by O~O yields N'~LN (because the result Is mathematically undefinedl, Iu C99, the a~ A,. e~1 B,~ f~ F~, g,and G conver Ion speelfier are capable of COJlVI_ C1Uo1g' these special value: J to a form Lhul can be' displayed, a. Ie f i and 19 couvert positi ~ve infinity to d.nf or j~n'fillity [either nne i" legal) negative infinity ItO' - Lnf or -infi.ni·ty~, and NaN to nan or -rian (possibly followed by a series of character. enclosed in parenthese ). A, E,. F~ and 'G are equivalent [0 a~, e-~ f,~ and g~ except that upper-ease letters are used (INF,~ INFINITY:, NAN) .

• . S'"PPOI,rI,Jo'r wide cl,afocterl .. Another .'99 feature j the ,abili'lY of fprintf

[0 write wide characters. The %lc conversion specification is u ed to write a single wide character; %:19 l: used for a. tring of wide charaeten .

• P,-e1~I,ioIIS~~ Illllld~fiJ,I,6d Con.ll"rlio,n' Iper:l/icdtiol,,' Riat" allo'wetl., In C89 the effect ofusirl,g %le:1 'lE", %If,, t;lg" and %lG is undefined, 'These conversion specifications are I,eg·all-in 1C99 (the 1 length modifier 'is imply ignored)"

Examples olf .... ~p,r,i,n t f' I onverslon S _-' ecitilc,atiOJ1S

Whew! It sabout time for a few examples. We'·'ve seen plenty of everyday Icon,' ersion specification ill previous chapters, $:0 we "'11 C( ncentrate here on i llustrs '( lung some of the more advanced ones" A,· in previou chapters, I II use I. [;0 represent the .space character,

Let'i start off by examining the effect of flags on 'be' %d conversion (they have it similar effect on culler conver ,10:0.,)., The first line of Table 22.,7 how" the effect ,of'%B,d withom any flags, Thenext four lines show the effect o_ t_he- -, +,~ space, and 0 'nugl~ (the # flag is never used with %d)I" The remaining lines show the effect of combinati ons of f),ags.,

I ~ 611 V'fJrSWJI ~: ,lflcifit1flt!fJJI

1l£s:ul1lfJJ~ ,p'l~"i',l, (IOI:'I'I1,I',i'),11, Ito l'2~l

Rles,tl~ til lI]!lJ';',lg ,C"'l1J~rS;Q,'" tFJI -12'J

%:Bd %-Bd %-+ad ,. Bcd·'

Q'

.1 I ••• 11.2] 12:3 ' •• 1 I. I ••

·, •• '.+~23 I •• 1 .' I •• ' l2 3 QIOOO:O~23 ""~12,3 11111 III. .123., •••

:.001001123 • 00001,,2.3

1.lli·· .... ,.123 -123." •• 1• .111' •• 1~123 .,,'i··,-123 -001001.2],

-1,23 Ill. 1111•

-1 ::23, I •• 1 .' I.,

-001001.23

-000012]

%OEld ~-*Sd

~ Ddl 'b- !U .• I

%+oa,d % OB·,d

rra ble ,22ji8 _ fit t of the _ 1 ~

Jlbll, Deer of Mlnimum - m,dtb and Pre! ' i 'j

the %0. '

xamplet of tbe

,I '"I hi,

.I!!!!!!!~I!J

til. , ,eff oct of '-hi ", flu OJl' h o, X :L 'g, and Ie; I 1 nver ion .

•••• 1113 ,····0173

I. '. '.,1, " • 7b

," •• -,1 Ox'7b

'.",' 11·'7B

··'·'·OX'7B

% " Bra t8x t"Bx '.::BX %#lBX tag 'I ,8g

%BG t ,BG

' ••• '.1 123 1.,12:3 ~ 000 _".1., -1,23

-123 ,. 000

f n pr ' i u~ ch pters, when displaying numb- r ~ T, bl- ~ 21 I she , h effec

,1 fa ' , I.:.. ."~ S Ol .' , UJ ,

\ e' J_ Ill.' d the minimum field and 1 recisi -n

-0 here ~ ,n -, '-'0· ,'[ "0 In l"le exampl s her '. Inst ead, I the minimum I. ld j th i' nd re i ion -n he t,8

IE

nver JDf]',

abl 2.101 iHus1r,ilt, bow he %g C'c_rTI ersion i pla "orne num -'f' in 1ie

f rm ,11d I her, in %f ortn, "~ll numb 'f" In th ' t~ 1 ' " ,e ,,-, ritten u. ing t e % !O 49

,CO<[1.V' rslon specification, _ h -oj 'tWI ' numb -r have ex ponents fat], " t 4,:',01 the 'r di pla e ~ in %e '[rm. Th n st ei b numl er ire di snla Ie 'UI in '1;f f emf

_ h ' 1" 1 t, numbers hal ,,' p 1 en less than -4, ',I (bl '~~rl displ: _ I d in %e

form,

-buzzwordUi

-bogus hogus bogu

•• Ib,ogu

bogu •

buz "'Wlord bus zwo,t:d, buzz '·"·bu"~?

. - ~11~1

b,uzz -

%--6,81 " .. 48 ,%6.,4,8,

\-6,,45

1~ 2 -450. 1':'3 '.6 12 I .5,

12, ,~45,

l .. 235e+05 l '. 2 5,e+ <04 1235-

12 3 ~ 5, 12~35

.. 235

0 .. 1235 0 .. 01235

10 .001235 o~oaD~235 1. 2,35e- 05 1.2, 5e~06

fsca,n1 scanf

ln the past, we've as nmed th 1 tile minimum field ~vidUl and precision VI sre COH .. taut .embedded in the format string. Putting th -rk . harac ter ' her _ ehher num""" b ~ r w uld nmndl- - 0 allow U" t specify it an, argum n . ifter the ~O[nlDt string, For x" mple the following calls 'of prin t f all produce tbe . arne output:

printf(n'6.4d~, i); print! ( I %* ~ 4CP', 6·, i); printf ( "·%',6 • *d! II i' 4, i); printflU%*.*dll, S, ,4, i);

Notice ha the v ues to b. fill ~'_ in [f' be '* .. om' jus t efore Lh _,_ tlue to be displayed, ~ . mnajor ,adv,~ mage of * .. b rh way~ i thll ill·,illo'w us I~O U~ a rna 'f0 to pecify (he ~ idth or precisk n:

prin f ( u % "k'd II r INI.DTII Ii) ;

Th most unusual speci flcatiom I we !!$qp and %n. he %p conven ,j, n allow U III plio the valu I f I pointer;

printf ( II %p I~ I (void")1 ptr);'

l'it Cii splays va.Lue of pltr * I

. ,Ilbougb %p t IO'~C' 1- ionall u etul during debu ing, i -" not s fe: 1 ur that mo~ t programmer' use an I daily basis, The t . tandard do" D"1 specif what a pointer 1, like \1vh n print d using %p, bu if- likely L I be sh .. n £1-, an I_ ctal 1 Ir he' ,Bdecimal number;

The '%n corr ersion is ued to find Qui how many sharacters have been printed r f; r -,y a c 111 'f mup,riol..ffE For ampf after th call

the value I. I" len wili -e 3,., ' ince pz Ln - f had written chara ter . ,(123 . b the time it reached %n! .... otic - tb~·t & Inu -'I precee , lien (b CQIIJN - !%n require ~ a pointer and that len h .. elf In: torin ed.

i ·,11 fscanf (FILE '* res' iet at. eam,

const; char • .reec r " ct fo'rmat, ,,);

Lrrt. acanf (can·st. char '* nesu.r i Cit ._ormat, );

fsc:anf nnd scanf read data items fTOlD an input - trearn .. ujn:g' a format stringte indican th I II out r the input, At" r tl f rmar s in, rr number of poinu -each pointi ,g to _ n objec'~~rouo. as additional argument .. Input Items ~ onve ted (aecordin to' conv ersion specifications in the format string) and : torcd i11 'the - e ubjec s.

scanf always read - from stdin the tandard input stream) whereas fscan,f reads from the stream indicated b)i its first argument

1* reads from Btdin *1
~ ) 1* reads fron fp *1
&J I
# A call 'of ecanf i . equivalent to acall of fscanf "lin1 s,t,din as the Illr','t argument,

The .. r.sc,anf funlctions return prernalurelyif iln ;'I])III'I"i1,"f,' occu - (nomore input characters could be read) or if a m'fJ't:c'llrng [ai/liTe occurs (the input ebarac(S)I ters dldn t match the format string). (In C99 .. an iDPU~ faUuTe ean i\t 0 occur because of un ,SflctJ,di'Il'M error; which mean tb,at an attempt wa made to read a

mU1Ubyten::hartU:18rB ""25,2 multibyte character; bu~ the input characters didn 't corre pond to any 'Valid multibyte character, r Both functions return he number f data Hems thai were mild and II~s,jgneu to objeets; they return B'DF if an input failure occurs before an'. data item can be read.

LOi ipS, 'that test ac anf s return value are' common in C program". The ro)]ow~ ing loop, for- example reads a series of 'integers one by one, iopping Illll the first ,slign IOf trouble:

}

u~sca'nf' Format Strings

Calls of the , ... acanf functions resemble those of the ." .. ,prin t f functions, That similarity can be misleading, howeventhe .",~s:canf functions, work quite differ ... ently from the ,,, .. printf functions. It plays to th-ink of acanf and, fs,canf as "pattern-matching" funetions. The format string represents a pattern that ,3. .. .aoanf function attempts .0 match as it reads input, If the input doesn't rnatch the format string" the function returns as soon as it defects the mismatch: the input character that didn' t match is ., pushed back" to be read in the future.

A inS canf format string ma,Y contain three things:

• Conversio« Iper;,;{i,c;ati Q',RS.. Conversion "peel fi,C'at·~OJls in. [J! -,.s c an f format string resemble those in a ~" .. prin,tf format string. Most conversion specifications. - kip whi ~e ... space characters at the begi-nning 0 r an input item (the excep .. lions are %- [(0' %c:,., Slid %;0). Conversion specifications never skip trailing whitespace character ,-, however~ If the input contain -1230:, the td conversion specification consumes I. ~ lOT 2,. and 3", but leaves c unread, (I' musing I. to represent the space character and C to represent the new-line character.)

.WlJit'~IPQC'" c'12Qrac'te,,·s~ One' or more consecutive white-space characters ill 8, ~'iI$c,anf for"m,a_1 string match zero lor more white-space characters in the input

stream"

• NIJI"'~ ~,"ltitf!~sPac'I" ClltlrO'lclten. Anon-w bite-space character otherthan % matches the .L ame character in thei I1pUt stream.

'Table 22 .. 11 Lensrh .. ' 'odi tiers I· r

a-

,~.,.s canf ' 'uncti . n.:

F II~ .. ' ample, the format string III I SEN %d - %d ~ %" ld - to 111 spe ·if~e· that the inpu' iU - - i. t o_f:

'lh, - I U ers I SB'N

possibly . ,onle white- "pace charact rs

.

an mreger

th '. - character

an integer (possibly lllC' xled by white- space characters) th - 'h~r- - ,-r

a long lnteger ,(pn.,sib~y PJf _ c',e'd·d by white-space cheraeters) Ih" - . haract r

an inti _ rip siblv nreced I y , hite- ... p, zharac rer )

... '- c,anf Cion ersion ...• : _ eet Ieatleus

Conversion I)Cl ifi,catio[l, , r u.sc,anf functions are . ctually '~ little .' impler than these for , .. ~,p'rintf functi am i A .... acanf conversion sp cification cons isu Ii the

charact r % t 11 c'- by the item Ii '_I d bel- (in til - rd r shov n .

• ':iV (OpUI aal), The pr sence of * si nif " QI." 1,,,,ne'II,' :"illpp're~,..ton': , n input it 'D1 ,L, read but 110l ~l: ,igned to an . bject, Items 1118~ch d using * aren l incl ud . ,in 'be C' r- thai wuS,C anf re urn".

ax;"1 g", (ie,ttl . idll, (. ption ' .. Th maximum ji ld width li 111i t th - n umber of chat acters in ~1r1 input item: con, . rs ion f the iretn ends if [his number i

jill . hi 'Ih t. . d a b .. f .

r " 1; o. ,I te-sp - _" cnaracn -r~ '~Al per at t -e e I nmna or iJJ onv -r ",11. '"

d. n l count.

• Len,g,II nloldij1er (optioual). 'Ih ~ presence rf a.I mgth modifier indica es that the e -6: 01 in' hlch the input ill sm 'ill be I ored hal'. I' e that's longer or h orter than i Dor.111a~ f ra particular conversi n pe "ificat],on. Table ~(l.lltjst each length modifier, the "on,'" rsi n ~p il1Ief~' wj h I: hi· h i[ m~r be used, an I the type indicated h. the ombinaric nor' the tw . ( n:, combination f length mod ... ifier land conversion pee ifier not shown in the table cau se . undefined behav ior,.)

sbor . int *' I, 'uns igned, shor't in't: -If

----~--------------

LonqLnt *- unsigned long int ..

~~---------------- ~~

double *

c. s.,or [

----~------ --~=--------------~'~--~

11' d, L, o, u ... x,~ X n Lonq lon.g Lnt; ~

(ell'~, ·UJ uns,ign.,ed long long int

I~- -------------------4

j t d,~ i. 10 UX~I X~ n intmaxt ,t t u.intmax t *

1--'= Z t S i z t * -~~------------------I

ptrdiff_t '"

t

long doubl,e'

~

II" lum'y

"n~ li"., I' 2,1 1 "1

.l.il.lllll_I, , il!!nl ~

II\, r' ion Specifier ~D"; . , .. s canf ~un" tions

---_

- -

• lOin ers ~'(J, spel:i er. The li ted in ~, ble 22.1~"

i ,111 m i lar sumed to have ryp I

Lrit; .. , TIle integer ~ m I umed to b in b' ,:.. ,to unl ss i'r begin v. ith 0 indicatin.g 0 'ull) orwith Ox, or OX ,hexadecimat).

a

u

Matche I dec 'iJ11D I i nteg! r: tb I .orre pending am-gum ru i a. sumed to hav l-ype unsign,e,d Lnt 'it,.

x .. X

Marches a h . adecimal integer; the llI~~I argument is assumed

tA have t pe unsi,gn~d int "* ~

~' At e E

iGlb.llI!l" ~ -_'Ii .

f, p1'~ g, G

~ ~ - ~-

',,'I atch I a Hoatincr'-pornt number; the corresponding argument i, assum tI [c have t '.e float ' . In C99. the numb r COOl b, lnfinit "sIN.

c

S Malefic" 0 sequenc ofnon .. whhe'-spaee I haracters, loon adds a nul ~ charact er ,l "II nd, be correspn ding argu ment ~ , :' umed Ito be 18 Pi inter to. character array,

[ M'aL_b '" · nunempt ieqnence of character from at scanset th III add a null charaeier aL the end, The cones p n lin~ argument is as' nrmed l be a pointer Lu a charmer HJ"f,)l1

p l ~ h I a pointer value in 'h, - form that ,I uprin .: f would h, - wri len

it he correspondlng an ument m' I III I sumed to be a poinrer tel IB void ~ ,bj,t:l.

n Tb,le"corrlcsponding argument mu~l pint I[. an ubjel·l oi Itype tnt.. StolT>C in rbi 0 ~jcl tho number f characters r"a, ~ . far by tW I call f

'.'. .acanf. - o input is 10 nsumed and III return valu - I f II U acanf tn'l

a~ I " [ell

tlC991 e nJ Y

Numeric data Items can always begin with a ',i.E!'D +Ir -). The ocu, x and x Ii: pe ifllefL Icon ,,:rt ~-h- item t ' unsign d form, ho ev I .' thev Ire [JOlt normally U'~_ tu read negative 'Dumb -I ' ..

The [ specifier 11 ~, m 'rle complicated (and mote flexible) vers ion of the 19

'I ~Iejfile .. A mnle e " n I r i n speci icati n using [ ha: th,- form ~ [I r] OJ % [A,le1] .whcre 'lllc~Ul be any sel ot charaet {I" (If] i on " ~ the chat91cter in let, how ' er, i L must come fi -,. st. I %: [.' I] 111:_ .tch, 'I ,1]' seq UIf!II.ce of character in I ' t , tbe s -a-I I,et). t [A !'Ii?l'] rnatche any sequene I of har c' iers "0' inel (in 01 , r word ~ the '" canset consi 't of all characters n 'I in sle'r). . or example, %7 [ablel]

562 Chap'lt6'r22 ,/nputltOutput

mat hes any sn I containing nly the Iller a b, and c while ,t ['''ab,e] rn tehe --- any string hat doe: n' t 'C(][1r ln ,a, bWI or c.

, W1 or th - , .... acarif conversion I peciflcrs are clo -, _Jy related tOI hie numeric'

numeric canvs _Ion fiJ"- iellS 11'-28.,2 I, 'I n er ion functions in <stdl is "h.~. Thes e functions convert trings (like

If - ,,2 9 7 ~~ • ' their equivalent numeri v, tue I (-,w:7). The d - pecifier, for _, ample JOI' - r ,. 'n epti mal + or -ign;jj followed bl( a series of decimal di 'jt ,! thi ,": exactly the.same form ths t the S' .rtol function r quir , when ,m ke to con - r a string 0 a decimal number, Table 22~ 13 show the C'lITI spondenee between I 'onv rslon sp cifiers and numeric (:011- " r, ion functions,

Thbllll~]3 Correspundem ,- bel een ... acanf COD. cr. ion Speclfie s and 'umerL I onv rsion 'Illlil ti m

A ~

i

o

,sLLtoul s r oul st.r,oul 91trtod

It p,: y~ 0 be arefll~ when ritlna calls of s,canf .. An invalid eon, '.- r ion .. pecificaDOll in a acanf -OTmat string i- jn --I a bad 3, one' in a printf format string; either one' c "USleC unde fined behavior"

h conversion pecifi "ann- for aoanf nd f,Bcanf h· ve undergone om

chang "" in C',9 burth U t in 't· I exten i' e a' iI" Ior Itbe n printf func io'O'S::

• AIIdltIOl.,d/l leJlgl-II"-'(J,tI}/i PSI C' 9 a Ids tile' hh, 11 j ~I z, and t I ngth modifier . Thee correspond to the len th modifiers in ~uplrin't.£ C nversioo specifi-

.

ca ion s,

• :dtlf~o ,-at C,OIJ"p'e -S,i:(ji I'pe I,iJier. ,.1 -'g' dds th ' F a andAc nversi m p. "~1 fi~

C[;-. The, '~f pre 'lid ~ ,- r lynUTI_' ith u",prin,tf; Ilb .;o~Bc,anf fun ti n~

tr 311 tbm the-same as e101 E" f g, and G~

I. .'. - ~lit " to "Il'ad i~fiJli ;-' G d . '(J, "Jt~ 1 0El "" Lb·. t ... prin t f fnnc ti ". . [', D . rin

infinl ty d N" '.. .he ... ,s c anf'un "i ns . ~an, ~ II the C . ',81 u '_ .. 11 be [I·· ad P!"OP rl"~, they '11 uld hut e th ~ sarru appear mce. -, aJ 1I.~ written b~, th ' ,,~,.prin'tI unction ~ , ith ca: I b ing ignored. For e .ampl ,illber INFr inf . ill -. re d ~_. infinitv,

• Srrppolr;t /0" lV'idl! .·h.rllc,terr. Tbe .. ~!!scanf functio ' are able to rlead multiby e character I w bleb ar then convertedte wide' eharaet -f,-, , for :. torage .. T_ e tic conversion spe lfication is u sed to read a singl murLib~ t character or a

Lqble 22 . .14 acanf Examples (Or up I)

'T: ble 12~ Is, can't Exampl " (Group J

sequ nee of multibyte eb F' ters: %1,9 is U', 0 lie-ad ~_ i ing . f D1UUib_ (_ ha' -t,er (a null ,h,arLU;l· r i ad I d 'I h - end ~ The %1 [s ,t] and % 1 [A _ t] conversion specifk arions can also read a ,- tring of multibyte eharaeter ~

,SC, an f Examples

Th next three ta I I s .contain amp le calls 'of s carrf. Each call i, j),PP lied to the

input ~ haracter sho n t its ri ht, Charaen T print d in . - c n umed

'~ the call, The values of the v iabk s aFter th "an appear to the rii ht of til input,

The examples in Ta le 2~,,1 h~'" the I ., I or combining ;Inv:_-c· ion spe iHc tions I white- pa ,'II, charact srs and non-whit -spae , characters. In thre,· IC&''1;e' I, no V'~ Ju ls a ,igned to j ~ , 0 it r bun, lu value from efore ID_ call 'f acanf, The 'W11pt~ in Ta de 22" I' . h ,,' , the e ~ '- [ a signrne 1 suppressii n and - p, cif ing a field width. The examples ill Table 22. J ~ illustrate th more esoteri ~, converslon ~ pecifie: L, [,~ and n),

n: I -il. P)

.... I! 1_-

~: unchang d,

&j ) ;

n -

n:l i: L~ " 4 ]I:, '

n:

L: 3-

~ <']1

D.: ~'I

n ';: acanf 't 'II %ld%2,d·'3,d~11 ~'

&i ~ &j, .. I -,) ;

I, . 1

1: I

j: 23

k: - -

~,

n - scanf ( ~I~ %2d%2s,%2d" j1 &.1 I etr I ,&j 'I ,;

n: 3 i: l~,

9 tr-: II 34 11 j: 5'6

Tabl·' 221w,16 scan.f Example ' ..•.•. roup 3)

n: 3

_0 .. I?

~,~ . ~

BU'I ho . can ·1 U - hi-b ind of tailure occum ,,; In many case: it d sesn' 01(1,1-

r:'Qme hing . ent -- ro ! '" 'lid '"I~' '.' - '_ ot 1 • ab-=. nd I' tho pr, '·n m. h r be

tinl. t he, 'f·r, vhen . Ie 11 n __ ' pinpoin the r~· I In f r the ,<, • .H' e.

very stres . ha. two indicator ns~ 10 -i ted with it. an erro indi Q_IOI!l',Und ' n ,ell"d-of-ftle'i",di ;ata·~ Th':." e indicators are cles red when tl str enm i op ned, - l surprisingh i' encounterin i1f end- f-f h:: -'I ts the end-: f-f lie in.' icau r, and u rlerd d . rror '-,,' the rror Indicator, (The uror indi tnt i ,01 -~et - 11.1111 a . rite nror occur on

an output stream.) .', matchins allure d I, . n't changeeith r indj -at If.

clearerr Once' '- _cITI'r en '...-f-fil ' indic at r i' set, it rem in in tlu r s 'L_ until it .:

expli ~jd- cleared.perhaps b a aU I f the cle,arerr nction, Gl,ear,err IL:) ar both tb 'end ... 1 '1_ -file and error indicatn s:

. , ~ f ~ III t!!. • 0 i Q. • II r. • &j

,n - scan . I~ 11' 1. ~ ~·1 I: or;J.,. _ ,

j:' II, k: 18,

n: I

str~ II~ 123, II

n - acanf (1111 %' [012~, '567,B9] '11" s tr) ;

n~O

s r: un·hanged

I--------~~--~--------~--------------------~----~---

n: 1

str: . 'a:bcU

abel,2.3C

.n: ~

s , '10'

~ . ...;.,.

j:_-

vo~ c earerr (FILE, *stream)'; ist feaf(FLLE *8 r. am);

int fe I'o:!:" (FILE *s'trea'm) ;

H we ask ,I ;;"'iscanf ~un_li In lor sad antl tore n de. ,I items, 'we I xpect its return

valu t be n. 1 ~ the n 'turn . Ilue], 1" . than n, ~r mething . ent ~ rong. There ar

th ree P I ;si hili ti'· s .. '

• EUli'~(}f-fill!'i The functl n lene unt .. ed . nd ... o ' ... fllc be fa -1- matching til . format string .. ornpk 'tel)'.

• Relld erro fj I 11 un i, n - '_. ru nable I _ r sad h, r,a. t r '~Im the :rc . 01.

11- at IlfN" ,JitlirlTt..' dO'1 a item ,',a'., in lh· ' T1I1g format, For .". ampl " the fum '(ion migh have len I untered lie' er ' hile sarch ing fer tile f lU di 1

;ill1 int ' .. e'r,

c'learerr ~fp) i

III

feof

ferro,r

1111'

221,3 Pormetted lID 565

cl,earerr isn't n eded often since som of the ether Hbf,ar~ rune LID, clear one or b th indicator ,B" a ,," ide' ffe t.

WecancaH the fecf, nd ferror.: run '[iDL'tO"~,1 -, am's in icat I[';,_I'

d -'L rmine '. h-' · )lti, Ir oper tion I)] lh "',t learn failed. Tl e call f eof (fp ) lie-urns ~ nonze 0 ' alu if the ,: d"'IQ .. fil indic tor i .. t fo the tream c. 1,1, ciar d with f'p. TIle call ferror' (fp) returns a n mz r ,,, lu, if the ern r indicator is set: Both fu ncti ons return z, r- otherwl e.

When s,canf retnrn: a small r-than- xpe _ ted value C~ n u -e - eof and

ferror t d' termin ,,' the ,reaSIOD~ " feof re turns a nonzero nlu ,. W:- e reach d the end of the input file, ,I fer'ror returns , n nr raJu ,~, a .ead "no oCUIT_d

during input. U n ith r 1i,(U ms a nonzer alue, m chin _']11 01" t h'" e I ~-

I. urreo, Re M -1 co f _' hhe pr ble m ,_! -, fhl return _ alue of scanf t It u

110 many data items wen readbefor th problern t curred,

To see ho, freof and fe,rror mi II be used, lef'. write a function thet arche ,I file for 3. Iine that begin ~ with an integer. Here' bow we inten tc call tb - functi on:

n = find int I( II foo 11)1 ;-

.......

n foo" i the I ame I _ the fit

intege r that it find' ~ which is U1 be epened.. I n ad _ rr Ir 0',_, urs,

return an error CI de (- ~ " -2'1 or begin with anegarivt i: nteger,

th,

~

can 1

m line begins \1 ilth n 'intel!er-find~il1t' i1.1 ~I,. resp ctivel J m 1"1] 3· ~ urne 'thr~ I 110 Iin in the file

int find int (conac chaz *filename)'

{

FILE: . fp = fopBn(filen,ame~ "'r"} t int n r

it r( f'p == NOLL) rs'tur'n -1 i

while ('fscanf (fp, 11I%:ldil ~ &on) ~;;;).) .( if (fe.rror(fp)} {

r-close (fpr) .~

1* r ad eF-or*1

1

Lf (f,@,of ( I_p) 'I {

c oae (f'p) ;,

zet.urn - 3 j'

1* inte'ger not fO'und I

}

fec,anf ( f P II 'Ii ~J{* [~\n] If ) ;

1ft ak.ipe rest of' line *-1

}

fclos,e {fpJ ; ~eturn n;

}

-h whilel contr Iling ... p~ . ioncall fs,canfjn __ n attempt to re din

in be tile. f the a' t nnpt foH s f 6, Call£ r turn "- - al U loth: r Lh·, n I),

find~~nt calls ferror and fee "00 see i Lbe pro I Iem as . _ a ,eD'iOTI' r ndof-tile. If no fscanf mu ,t na e aile. because :f ~ matching rrc find intkip- tll' restof the ch racter on the c rr t line and trie: ag in. the use or h- conv rsion 0 * [\n] to 'Ki' U ch racter .. UPI Ito the- next J] . -Iin .. {, ow' th~ I W kno .. b nn I: an ee '" i ' time to how .. ff! .

10 this s c l n, .',,"U_omh1·1 libnu fur ction that read and writesin J' baraeter .. These functions w rk equally 'well V\ ith te a stre ar - .' and 'inm-y str ram -.

You U notice that the fun I 'li~ n ~ in thirL section treat characters a - aloes I If t p. in,t- not ehar. One rea n j,' [hat '_ ~ _' input func 1.',0 Indic 'lie' n nd-of-file t .' rror I c nditi n 'b~ll"e urning EQF which ts :~ ne b,a i e integerc n 'tant~

0.' tpn FDn -'tions:

i -t fputc( tnt e , FILE *str-am.) i m'- put;c (int OJ FILE *strem)l; in pu t ,char (u:r c);

pu'tchar' put.chaz writ .'. one charact r to the stdout .~ tream:

putcha ~ch),;

t= wri tle·s ch t.o s douc .. I

fpute pule

f'put.c and putlc re more general .. rsion of put cha.r th~ t writ ,an arbitrary '. tream:

fputc (ch~ fp') i' put.e (ch , fp)';

,. writes ch to fp */ t- 'writes ch tG fp *1

Ithough putc and fpu,tc do . he same thing, put;c is usually Implemented at a macro ( " wen as a function), wbd - fp,utc i .Implerm Died only ~U~ & function. put char' itself ~ U BaBy a macr define _J in the foll ' ing : ~ v:

.1 define putcha r (10) putc l( (c), ~rtdou'l:)

[l --, ·'m. dd thai tb I libra . pr vid • bo h putic and fput,C'~ But, · · ,e'3W in I. ecti 'n 1 L '. ~ mac "'D' h:' I e e," -'"81,p t ~ ntis ] p._ ble s, Tile ' . ndanl all ' ' he put,c m cro to IC' uate the st-ream rgurnenr .nOI'. m mce which fputc isn t permi t ed to du"AI[b . ugh pc -gr,am'ml r u ~'lUIHy prefer put;o, whi "h ive , a f:' uer program, f'put,c is Ilvailable" .an alt -m, tiv ,~

If u \ rit ~ I -or oc ~ urs, all rhr ee in. ii . th, erroi ind i I· t r for be tream

and r. ' urn EOFw o h ·rwi.s'e they r ·t- [n the . har 11] r . ha \ tit' D.

fgetc (FILE *st:rle,am.);

int get€ (I ~LE trelam, i

:lot getc:har ("oid), ;

unge C (t,ut c , F ILB * s em);

/ .. reads at ah,aracter 'f rom s tdin *' I

f'getc fget,c ,- Iget,c ead n I haracter from an arbitr getc

ch - fgle t c (fp') !lI! 1* rea,ds, a character fr'Q,m fP I
( .
oh - 'getc: I(fp) • I"" read,s a charact,e,r from p ,I
~ " ll thre - fUD''''IJ D' treat th 'char ter as an un,81gne,d cbaz : ue (whi h j the n converted I~ int type I'~ fie if,. returned), A' II result, [hi} never return.a negaive - alue !lh-r - :' E'OF'.

The relation .. rup b L, een 'g,et1c ,nd fg,etc L similar to tb I between put;c

and fpu c 'gletc i~ usuall irnpl m nt d a In u ro as, well . __ . function

whilet qet.c · . irnplernente only . c uncti 'D., 'getehar i· Df rmall a m,acr '," '. w H:

#d,efin,e getcbar () getc (std,in)

For n ading ,cb,_ .~. , 'fer: .from. file pro amm rs 11' U IU, pn ._T getc . - .iT' fget·e" Since get,c. is normall a· ailable in rm ern firm it t nd obe fa' er. fget c can

. used a backup if qet.c lsn t . ,PILfP ia~ . [he standard . Uq . tl. 'getc

rna "[0 . I[) I,· aluat irs argument more than on e which may be a problem.)

TItI fgetc gate: and getchar un lion, beh ' esarne if a problem

C cur '. 'tnd~ I-ril,e . he', set the str am ~" en I .. .of .... - 1_ iII i:. ator land retr 'E:OF,., If t the ,- trearns error indir - or ,'0 d. r,elurnE:O';F~ I. di_-_ ersituatir n .~' ~ ". an all e ither II eof I Jr ferror,

: the mos Cnln1011 uses o .; fgetc.~ qet.c, ~ nd 'get,cha,r i ,eb' '.' tier fr rn a file, . L' by -0'-, until end-of-tile '. '. UI~. It '. oust ms . t Iollowing whi Le loop for thn.t purpo ' ;

to read

~ - - --

D'1' the

idiom while I( (ch - ge'tC' (fp)), ! ~ EOF) {

}

After reading a characn r from the it - _ .. ' o· iatedwith fp and storing it in tile variabl ch which must be o_ type int)_ the, while' n t I' nnpares ch ith E'OF oh isn t .~ mal to EOF~, we're notat the end f tbe file et so the bo _y of the loop' is exec uted, If ch i u il to EO'F the 1 .' :,cr _ in, __ ~'~I~

&

,

II

ungetc

-Iw, ys store 111_' _I tum valu f fgetc, gleec or Igetohar in an int ariable

not a char varia, 1)1 " Testin a char an" 131,1 -, alnst EIOFI I giVIC the, ron

result.

Tbl r, -: I ne other char _.CL_f inpu .', merion, ungetc - bich "push back" a I. haract r load _f m a stn am andol ar 'h ott sam ' end ... , '-fit 'indic l'if. This capabilif can be h n 1 if need a "l ab ad" char cter durina input, For instance, [0 read ~ series 0; digit stepping at [hie fir, t nondigit we could write

}

ungetc"'ch~, fp,),;

1'* puahea back last ,ch,aractez re '. d *' I

Th - numbe cho ' '. ·'~·r' that can be pushed "I' c b '0 ecutive I. n to

ungietc~witb []O inten '-ll[]I_ re ~ d ope n till' I -·r-del end" on the implem .nta Ion and the t pe 0 stream invol ed; onlythe fin - call j: guarantee to succeed Calling

'ti~e,pr;"sitlonlnIQ (,unctions .82.1 - file-po sitioning function (f seek .. f setpI,es, t' I" rlew ind 1 I 'O~lU:' es the PUI ledba k charact -" b: be lost.

unqet.c return: th ' .' haracter it wa~ a ked to pu ·b bac ~ tOIW' 'r.~, it return EOF if anattempt is made t. oush bac EIOF or to' pu h back more h racn r than the implernen ration ,al1o ." , ' ..

P'AOGRAM

The f Ilowmg prl e l m m e a cop I. r s I-e~ , .nam the rigiual fik and

the neVi il . ilJI be i pecified on the c, mmand lin ,h n the program i execun , .

F 'r ex: mple toe p. th '""} fl. ,. c l! f2- ~ c U u~ e th _ Ie rnma '_.d

fcopy fl.c E2 .. c

f eopy ~,~ ill i IUJ.: ,n er 0- m ',,," '_ lei ~ , h I" i aren ~ l ex '. t1 to file nam n lhl'

I ommand lin or if < itb r file c an ~ t.b opene I"

fcopy.c 1* Copies a file */

\- include <stdio ~ h~ #in,clud,e ,::sltdlib.h~

in main (Lrrt. argo, chax *argv [] ]

{

F'ILE *source_£p, *dest_fp" int chi

_-

- - ---

22~5 Line 110 56~9'

1: fl I( argc ! "; 3) {

fprintf(st:d,err, ilus,age: fcopy aouz ce dest\nll); exit ,(EXIT' FAILURE) ;

}

if ((source_fp = f,opan (argv (1] ilrbU») =~ NOLL) { fprin'l: (sri de ""r, "Can't open %s\n'll, argv[l]);' exit (EXIT_FAILURE) ;

}

if ((des, 'P -= fopen (,argv [2] ~ wb II») == NtJI..L) { fprin'tf{stderr" nCanlt open %s\nll, argv[2]);' f,clo'se (s,ourc'e_fp) ;

exit (EXIT_F'AIL:qRB) ;

}

wl'lile {( ch putc:(oh

- g2'tC'(so rc::e_fp)) != EQ17') dest _,fp,) ;

fclo:se (,siQ'urc,el~fp) ; fclQse (d,es,t_£p)' ; re turn rJt ,;

}

Using ~'rbn and J"wbU (-IL' the tile rn d.'s enabler fcopy t cop' both tex rmd bin " iI~. If" , I used nrU and '1118111 inste It!L the program w uidn't necess 'ti1,~ be able to -'opy binary 11 ~Ie~', .

w. ~ ,II n ".C- turn to librarv func ti .In at re _,d and writ lin" ~ The e fun tJ un:s are

~

used mostly with te t tream~ . al1J ugh if legal lJI U _. them ith hinar ~eanl·

it, ell.

Output

int pu ' s (canst elJ,a,r _J;:-est ie,s,

FI, " .. res i.ct: at -- m); int pubs (cons char *' 9) ;

puts, We,Jnco!Un~erled th puts function in . e lion J_· .. 3; it , rites a string 0' charac r· to at.dout.:

fp'U[ls, fputs is ,~ m' r general versi n I f PU'-'SE Il

stream to which the output ~ hould b v rit en':

Unlike' PU,t,S. the fp~ute function doesn t write a n _ w-lin char cter un] pYle. '- nt i _ ~ .~,', - ing, -:.' 'tb fUI, io



~:, 0: ~Ie[ IS

fputs ( "Hi " t.hexel II'~, fp·) j'

r tum EO

'ctr . ~

til ~L

enA'l c .. to .

nonnegative number.

char *fgets(char * estrie~ sit n, FILE * restric a-:eam); char *gets(char *6);

IQle·ts The gLets unction, . hi h w input from atdd,n:

gets '(str) i

1* reads a line from stdin *1

gets[ reads chara ters Ollie Izy ODe~ toring __ em il.n tile' array ,'. IDled t b,: st r until it Ji adi a new-line chara .. t r .' which it di cr rds),

fgets flgJets is [2Jj mol",' general ersion . gets th - n r' . - 3n_ ,tr'_~ m

f'g,et,s 1" also safer than gets,·'"nc _ i limit til- number of eh racters th. t I" will

tore, Here' 1 bow we might use fgets assu I' '_' that st~1 i the lam·· fa ,'b, -

acte 'f ar . y:

fgets(strt sizeof(str), fp) i

This call will cu e fglets tnl read chi' ere r until it reaches tli - first new-line charac er or sizeoef [( st.r) _" [ characters have b '_D n , d, whi hCV'6' happen fir . If i re d th It.' .. ·..,lin t:t~ acte ,fgets or is it I Ion with tb .

ters, C hus [gets nel r. tores the DI · .... line t 'bara_"tr,ll fgets someti 11.',;', " es.)

Both Iget 13 and fgets return a null 'point. I" jJ (; read error ccnrs or the rea b [h end I f'the input stream be' If toring anv haracter ' .r. ;. u U· call felof .~, fer ror tin determin 'hi h situati n ccurred.) Oth_r' i. e both return tb 'ir fin l argument, w hi' h Pi ints to the ,: rrev i . which the input w . toted,

s. you'd exp ct, both funco,' ,n~' ~ " r, a ull eharac er I' h .en . tring ..

':~ow thIILl.YI\l'U know, b ut ,fgets rid" .gg [t usin it instead . f get,s · mo t ~ ituations. ith Iget 16 b ere ilJwa' the p ssibility 0 .~ pping u ide fhe b und of tb re ~ ivins ,~'I a~,' '1 it [.: I "I' to U' e nly hen tho -in. be·11D" r a - L,

I . uaranteed to ., tin' 10 the 'I -, " - , bien there's no guarantee (an ther usuall

isn it's much safern u·'fg,etsji, t lhatfgstswiUire'ft, rom.the standard inpu : uream if p ssed stdin. it third argument:

22-' &-

, ~-, 1-

" , I

!_ iii ,_. '_,

a i.z e t freald{vo~d .. resuict: ptr"

size t si.ae, Bize~t nmemb, FILE * res·tric,t stre,am} i

si,ze t w,rit@'(const vodd '* :restri,~t. ptr, "Si.ze t s i ae, siz,e=t nmemb , F'ILE 7: restrict stream) J

The .f rea,d and fwr i t e fun ction s all ow a program to rea€! and write iarge blocks of data in a single step .. , fr@ad and fwri t.e are used primarily with binary streams, aJtbrOug'h-willi care-if,s possible tit] use them witb text stream as well,

-

fwrilte fwrite is designed 'to ,ceip'y an array from memory to a stream, 'The first

argument ill a call of f'write is, the array's address, the second argument is 'U1e size rof each alTtly element (in byt:es), and the third argument i·, the number of ele .... meats to write, Tbe fourth argument is n file pointer, indicating where tile data should be written. To write the entire contents 'of the' ~a.y a, for instance, 'we could use the following c'.aH of ,fwr:i t e:

fwrite(a~ si2eof(a[O])f Si290f(a) I ~izeof(a[O])r fp);

There's no rule that we have to write the entire array: we could just as easily write any pornon of it fwr it e returns, the number of elements (tu,'l' byres) Rem ... ally written. This number wi]] be Iess thou the third argument if ,a, write error occurs,

tread fr,ead, will read tile elements of an array from a stream, fr:ead'''~-,· arguments

are similar to fwri t.E"!;,: the array's address, 'the size of each -element I i.n bytes), the number of elements to read .. and a file pointer, TOt read the contents of IEl file into the array a.we might use the follewing call of fread:

n = fread(a, Bizeof(a[D])~· si2eot(a) I aizeof(a[Q]). fpl;

If's important 'to check fr'ea,ds, return valu .. which indicate I 'the actual number of elements (nO't by tes) read. This number should equal the' :drd ar:gunlcn - unless the' end of the input file W'8S reached olr a read error occurred .. The' f'eof' and ferror' functions Clan be used to determine the ]1!a~OD for any shortage ..

A\ ~

fread(a~ 1~ 100~ fp)

We'-.rf asking fread~o read 100 one-byte elements S'D it will return a -VaJUIC

betw en o and ]00,., The L llowiu 'aU ILJLLl'lI"'-"'~' fr1ead to read one bl ·cl 0 100 byt , :

fF~ad (a , 1001, ~, fp)

fre'ad,", r -turn value in this casewill 1 eith 'f 0 ur L

fw:r i e is con enient f r a program lnal n " to t -)"1 data in ,8 fil - b f re

terminating. Later, th - rr . ram ( r '_ nether pro - ram for that m llet) can use frelad It . 1"1 lid the U,8 '.' ba into memory. D' sspitc t1 ppearanc '., tile data doesn't need (" be in ar]"a,~ form: fread WId fwrite w rk jus -' well with ariables f "II kinds, SILrW, tures ~ in -, _ ieul _ C" n brad freadlf ritten b fwri teo To write stru ture v rile 9 to a fit- ~;r instance. W~ coul use the sllowine call f f'wri'l:e:

f'wr!te (&:s, sizeof 1(8) r 1~ fp);

Be care I-.~ - n u in fwrit.le' - d ut tru tur . that ·U(J,,,,,~ P1lD[If aluei ~

lillie' 'e values ~ 'n"t auarante d t . b . alid " hen read I, ck.in,

... -

in - fge~_ pos (FILE * Jf'est ict: stre,am, f" 0'8 t. 1: rest· ~ct pos l ;

int feee (FILE *ste m~ long 10 effset, int w1ence : in fse'tpoB {FILE irstreamlt €IOIlSt fpos t,pos) i

-

long' int ft:ell (F LE s,t.r.eall1);

~O,i,d rewin,d (FILE ~stre.am);

fseek

er rream ha n " . iat _.fiJ po,~JiO"'~ bon _11 ·IP ne 'OJ the fih posi-

li n i ' .' -1 at 'It b, ginning '.f the _ ~ 11 ~ 1 If the fil j . .I" penet in a pend mode how-

ever, th initial til' '-0 i '( n 'rna b' at the beginning orend of th file, I '_ pendin

on the imp! ~ m ntation. Then, - he n are ·11,' or ',ri .,' ~ srati ] i' , performed, tho file position ad ances automa ic" UY~I ~ill wing u·· to [DOVe through the fll in a s mential manner,

,~. lthough sequenti ace . S is fine 'or man· appli ~i1U .In· ~ som _ program: nee the . biJjt t. jump ~ r un - -]-lI11]1 a, fllr, ,rJC' , I ini . m ds ta h -( - and othe 'dn,

there, I_' a file . , ntalns a series . f Fe ords Ior exampl ~ ight ~l_ ant to jurnt

dlrectl t 3 _ articul" record and rea H or \1 'Id~ t h. c:stdio ,.,h> upport thi form of DC ess by prnviding fu functi Ins, thatalkn ,8 pc gram to d, tern, in ... the current lile POI ilion 0[" 'to change ir,

The fseek function changes h rille po ,iti [J . 'S{ ciated with th - first argument (~ fil p. int n, The third argum ent . 'PI cifie . hetu ~r the nev po ition is to

b ' calculated with respect to the beginning of [hie file, the current pusirlon, or the end, 101f' the file. <:stdi,o ," h> defin . three macros rOJ" this purpose:

SEEK ,SET Beginning f tile

SEEK (~llR Current file position

SEEK END End of file

The second IgUI11,en'l is - (possibly negative) byt CO ILl nt.To (nove to [be beginning of a file'! for exampb ~ the s .-e.k direction \'inuJd be SEEK_.SET and the' byte' count would be zero:

fsee'k_ (fp, OL, SEEK_S'ET1;

fseek (fp'I O'L, SEJ~~K._END};

1* move9 to end. of file "'/

Tomove back, ]0 bytes, the ~. ee '~ dlrection wou'Jd be SEEK ~ CUR and the byte count WULJ ld be -l 0":

Note that the byte count has type long Lnt; so l've U' ed OL and -lOL as arguments, ¢ QI and ~ 1'0 would also work, of course.xlnc . argumenn arc C1D",' rted [0 the prOIJ ertype (;1 utomatically, )

oflJUlHy .. f,seek returns zero, ~r an 'error occurs (the requested position doesn t exist, for example), fs,e'ek return a nonz rIO value.

The file-positloning functions are best u ed wLh binary streams, by the way" C doesn't prohlbh programs from using them with textstreams .. but care is required because of operating system differences .. fSEek in particular L, sensitive to. whether a stream is text Of' binary, FI(u· text streams, either (; ~ ) offset ff seek's second aflgl.:unent) must be zero or (2) whence (its third argument) must b SEEK_, SJE:T' and off s@tav.ah.l,e·obtained'bytllprevious,cailiollit·ell., (fn other w' rds, we can oldy use fsee:k to move to the beginning or end of a text : tream or 'lD return to a place that was 'Visit[,ed pre· iously.) For binary nrearn , f seeki n 't required to support calls in which whenc'e is ,SEBK_E,ND~

naH Tile f t, ell function returns the urrem ru position asa .~ Ol11g hl[t~g,et. (If an

e.rrnoWifi,FatI'~el"24~2 error occurs .. ft,ell returns -lL and stores an error code in ,errno,) The value renrrned by ft,ell may be saved and later supplied to a call of fEH~!ek ... making it possible to return 00 a previous file position;

Lonq file pos ,

- -=

file_po,g ~ f'tell (£p) "

fseek {fp t £i lie pos 1 SE.EK SET) ;'

_.. -

r- l.-e'turns to old position '*1

U-' fpl i ,iJ hi nary stre am, the cal) f tell ( f p) return s the c urrent 6 le pns;,i U O,D. as ,a -,y'l_ count, where zero represent " the beginning of the file. ~f fp 'is a text stream, however, ft.e l.L (fp) isn't necessarily a byte count. ' a result, jJ s best net to perform arithmetic 011 values returned by ftell .or example, ifis n01 a good

ewind

fgetpos fsetpos

BEl

ide t u t~ ct Blue' return d : ' r-tell I ,I, e - ho ar apar ' "-"0 file positlon

are,

The' rewind '-w]} ti01111_ tl Ol_, fil,,1tion at th - be inning The call

rewin,ld(fp) i, nearly equivalent to fS'Eek(fp" OL, SEEK_S.ET). e dif-

f - rence'i rewind doesn 't return a value bul d )1 ~I cle . the error in.di ator for fp~,

fSleek an ft.ell h ' one _ r ble _t he re limit d ro '_d :.I'.J· e p sition [;.1111 b ,.1- fled in 1"1 long int ger, or workin ' i th very large filer i' provide I I' klitional functi n I.: fgetposnld fsetpos,. The funeti ,M IWI band) large fih b cause tb y 11 e values o ' p_ fpos_t . represent file ,pt' iUOfll'\ An fpos_t value isn t neee. sarily an integer: il " . 'Old - e a structure .. ~,. I instan e.

The can fgetpcls (fp'l: I.ffile_Plos)1 tore tJ, file posltion associ ted with fp,.in til. "ilep'o's ari -1[. be call fsetp.os (fp ~&fileycB ) lit th rue po litl: 11 lor fp [I I be, the I." Ju I stored in file_' pas. - hi. valuemu: t have 'been obtained b,' pte lou ~,', U uf fgetpos.' lfa "Wan 0 ~ getpos ',1 fsetp'os fails, it ~ tore an C ,r' d _. in e r rno. B th fun ·t1 n' r turn zer wh n the sueceed and a nonzero al ue when they fail,

H re how we might n"i fge ~P'O'8 ~ fsetpos t file ' ,i[i,on - nd

return to it later:

fP'OB tfile pos;

........ -

t= re'tu:t;l.1s to old, poa.i.t.Lon * I

The fnllowine program opens I, binary file containing part tructure read ~ tJ1C : nructu I : intr an am ,_ ., Jel" on .hand m ~.lnb~ r _ f I_ a l. strue ture to I'~I and th 0

, -

'write the .' uctures back t 'tIl f 1 '" N ~, that the program en, the file in

III rb+ u mod 1 allowlns both readin and riling.

In",c:Jeal~c IlfI" ,Modi iea- a file of part FleeSI: ds by set ing the qllatlti.1:y on hand t"IO zJero :fo,l: all eco de * I

include <stdio.h> #inclulde <,stdlfb"h>

i'defiD'e m..ME Lmf 2,5

-:

#'define 'MAX P.ARTS· LO'.(~I

st.ruct part ,{

-( ! t numbe r,

char nam.e [~_LEN ' ~l ; iIlt o:'D_ha.nd;

} in'lentery [R74X_PARTS,] ;

int num_pa,rts;

int main(vo* Id)

{

FILE *fp;

i.rr

if (' (p = fop'ern (u inven'tory. dat; II, 11.1 r}j- 11)) == NOLLJ { fprintf I( El'tdlerr, 1'~Can II·t open inventory file \n11l) ,: exill: (E'X'IT~FAlLURE) ;'

}

num_Pla,rts - fre~ad (inventory, sizeo,f Cetruct pa,rt), MAX ~ PARTS: ~ fp,) ,.

fo,r (i = 0; i -e numyarts i i++)1 Lnvent ory [il .. on~hand ~ 0 ~

re:wind "~p) ;'

fwrite {invent1ory; sizeof (s-tru1ct partJ # num_parts" fp)1 i fcllc;'Js~,e I(£pl) ;

}

Callin"rI8w'in,d L critical by the ,ny. After th fre,ad c Ith-' ill Pl' ition i at the end ·f the fU __ ft. ~, J f'write . ib utcalliu rewind first, f'writeu·ldaddne~ .. da Ib nd of the fil Instead of o .. er ricin' theold

The rune 'on' de cribed in thi iection _ ,1 bit UD.n ,u·_1.,inl' thev h, y, notbin .' to

do . ith ~. trearn ' or fill'~ In·.~ - a " tl all and '~_ rit -c. ," 'I U ing a <bing

as though i ere a tream. Tb sprintfn _ snprintf nn ti: In', rite char, ,_ ... ters int I '" _in. in the samewa thy rould be WI-'· ~ ,en I .... stream: he sscanf funl:ti n [' adR b acters fr ~ m ,i string as though it W If' reading from a stream, Th se Iuncti n 1)- hieb clost ly resei ble pr'int f and s'carif., are quite useful, s·p·rintf and snprint,f gi-' U 1 . p'rintf'\· formatting capabilitie

·]tbout aetu Uy havinu '. writ . ala to L_ stret mi. Similarlv, s,scanf give u tlCCC', , to s,canf, p.o. erful pattern-matching capabilities. The remainder of this section cover e., sprintf .. ,snprlllt.,f .. lind aacanf 10 detail ..

Thre imilar [unctions (v'spr'int' vsnprintf and V'S S'call I I als

belong [0 eat.d.i.o .. h», H. wever I these functions rely on the va_list typ.~ wbi 'h is declared in <st,darg ~ h'>~ I'Il postpone . liscussing th m until·, ection 26~] 'which covers that beade "

int sprintf(cha.:r "* .reet.r i e, 5,

const char * estric"t format, i.nt: snp'rint:f(c'ha'I * restrict e , size_t n, canst cbar • r'9s'trict format,

~ OJ

I!I! III '. I .,

l\'lllt .' In lhi and subsequent chapter ~ (11 pliOttOf.ype for afunetion lhlt is new ill 'C99 wil ~ be in ualies, I\~S(l~ the nam : o~"' the "nnclijoh wi ~I be ita ~jcized when it appears i n Ute [en marzin,

sprtntf The sprintf function l similar to printf and fp:rint-f,~ except that it writes output into it, character array (pointed to by its fir l argument] instead of a '. tream, Blprin,tf~~1 second argument is a format tring identical to that used by prin'tf and fprintf. For example, the call

'wiU write u 9/20/2 010 r, iUKO date. When it"~ finh;,hed wri~in,g into a strin • apx LrrtE add", a null character and returrn the number of characters stored (not counting the DUn character), If an encoding error .oecurs ( __ wide character could not be tran Jared into a valid multibyte character sprint.f returns 0 negative value,

sprintf ha a varie . of u e ., For example, we niigh:r occasionally want to formal data Ior output without actually v riting it. We can use apz-i.nt.f [0 do the formatting, then ave the result in a string until if's time to pI duce O'ULpUl. apr Lnt.f is a lso convenient or converting numbers to character form.

The snprintf function is the same us apr i.nt.f exce ~llt for the additional parameter n. No Iltu~.r,e than n ~ ~ characters 'fAl HI be written ttn I be stri nK'~, n,nt counting the tenninating null character, 'whi,c'h i "I always written unless n i zero. ( ~qui, 1-' alently, we could ay that szrp ri.nt f writes at most n character to' the string the last or \ hieh is a nul~ eharaeter.) For example, the 'call

will w d te ~'I' E ins t e Ln l Ai ~I intoname.

snprLntf return the number of characters that Wt uld have' bee'D written (not in luding me 11llU character) had ther , ben no length restriction, If' an encod~-ng error occurs, snprin-tf' returns a, negative number; Te seelf snpr'intf had room 'CO' write all 'the requested characters, we can test whether its, return value was nonnegative and less than n.,

Lnt; ss,canf I( canst char * res x i c t' S 1

consrr char *' reetzx ict: format" , .... ~);

Q& A 577'

sscant TIl- secanf function i _irnil, , [, . scanf and fscanf". except rbat it reads from a string {pointed '[0 by it: first araument instead of reading from ~ stream, ascanr-s . econd argum nt i· a tormat strin identical t I that U" d by scanf and facanf.

sscanf L han fir extracting data [rum a " ins mcJ ~_ a re input fun lion,. 'Of' X~ m I w might u fgets t . -;b ain a line Pi .- - lh· lin,' ," ascenf j} ·r further p'rol. I .': sim :

another ,- input then

fge~s(str# sizsof(str', s d~n); aaca J1f ( at.r , iii %'d%d 1m" &i , &j);

I '* re'ads a 1 me of input * I /* extr,act.s two in ,eg,ers ~ I

"'0 at untage of ing Bs·can· f scanf or fsrranf is m,31 e t an

-x mine an input llne s rnany times ., -" n e·~ ed. not j ~-,. ,t . .DC '.0; making it easier [.0 recogniz altemate input fonns and [0 r~, 'nv r from ·ITO);:. onsider lh problem 0' rer ding a dat thar' 'WI;. I n either in the fann ul(J'ntl1/ daJ:/yetir er IUfJ'l1th-cla'l'year. ,~ ssnming that str contains a line 10 '" input \ eean e-- tra I rh. month .. day .. and ye:u a- follows:

if (S!H7!,anf(st.r, "j'%'d ltd Itdu, ,&m,onth, &aay, &--ye,ar) == 3) printf(IIM:onth,: rs-,df day; %,d, y lar~ td\n". monbh , daYj yea~); el ae if I'sscant (str, lI'%d -%d -%d", &month~ &:day, &year) ~~ 3)1 print-(~Month: ~d, day; %d, yea ~ %d\n~, month, day, year); else

printf (UO,_ t,e not in the prop'er f.orm\n") ;

Like the scanf and fscanf fun tio]lo;'., aacanf returns the numb r or data items : IUCCes' fully read and rored, s scanf returns E,OF if it reach" the end 9- the I tring (marked by null ehararter) befor finding the fir t it - m ..

Q: If I: . IDp - - or 00 _IU redir lion , ill _he r dlree ed fiI'e namessh 'up iii. commaad-Ilae argum d111,~' .(PI 541]

A,: . O'~ Ute op rating :K,. I ·m remov er; them froJI11 the command lin . L ',~:"y [I, t

run a program by entering

demo fo'o cil1 file bar e-out; LLe haz

h . alue 0 azqc will be .J.. a" gv [0] ill POIOI to lb. pll gram name ar'g _- [l] will pOW' to ~'foo,t'~ argv i2J "HI point [0 Ubarll,~ and ,argv[3]

'. ill 1 .• int tin ba z II •

Q:

I b'u, b't 'tb _' tIle end, of _ lin' as 81,- avs mars '. b a new-hne C,_' B_.:t_:_r.

~

····0'0 .. on 'r' .'. ',yinl tha i_he end-r f-llne m··.r re one dep· nding 0'.0 _ ~. _ lOP' "iii

atin ~". t . m, - 0- ,IOU ',-)': in tb_is' di 'cf'eplanc:._? [piIJ-: 2]

- library functions make It appef"," a I thou 11 e~ lich line . nds . itb a "'U(I' n -" -Iine

I ! ~

A:

o.

I

.. . .,

A:

o.

. '. ': I!

character. Regardles _' of whether ,~IL input file con tain ' a carriage-return chai acter,

a line-feed character, or both 18 H - ruy functlon sueh I .'1 'g'etc will rerurn a single

new-line character; Th output function perform the re, erse translation. If a p'fi, - grwcn calls a librm-:y function to write 3 new-line character to a 51e.~ the function will translate 'the character into the appropriate end-of-line mark er .. C'sapproach make '- program more portnble and 'fl· zr re write; W' can wor wi: 1 ltexl fil, ',:, without having to 'worry about how end-of-line is actually represented, Note ['b,il'£ input/output p -rlormed on a fi1 ope ned in binary mode j n t subject tn any charaeter translaticn=-carriage return ,and line feed are treater] the arne a the other charact t .,

1- m 'w,ritml a ,p,[Qgram that needs tOI sav( data in a 61,e" fo b~, r,ead l_a'ter~ b' , another p1rogram_ ' ....•. It better to stere fhe I ~ ata in, 'lex!11D or bl~ - ~y , 01 - , ? [p, S4l

That d, ~ pends, H the data i all '~B'xl to I ltart w j th th re'·· not much difF renee. r L le data contains numbers," however, the decision \ tougher,

Binary form is usually preferable since it can be read and written qui "'k]~ .

Numbers are already in binary ~Drm, when stored in memory ,'-'0 copying them to D,

ih:~i is lea ,'1,. W'ritmng number in te .t form is much -1 we II Sill, -I eech nn - bet, mUI be converted (usually by fprin-tf) [. character form. Reading the -le later wHi a] 01 take more time, sine number will have Ito be converted frOJD text form back tJD binary, Moreover storing data in binary form often save:. space- 3!~1 we saw in Section 22., r.

B inary files 113V - 'tWOI disadvantages ho I er, They re hard for human La read, which can hamper debugging, Also binary files generally aren t portable from lone system [,0 MOth sr, since different kin,d'" of computers store datain lifferent ways .. For instance, snme machines store int values using "to by tes but oth r u se four bytes. There': also tb,ci isue of byte order I( big-endian . ersus littleendian) ,i

c " -)~-ogr,a'lDSfolr UNIX lie er I' eem 1"1 OB't tbe lett;e, ~ .. D, in the mede . .tring, e em = h,D"ib,nle be'inK upenled is binary .. ' b,at gi .. ~Sl? Pi .. 5'4, .]

In UNIX:~ text file I and binary file 113 e exactly the same format, so there 1S, never aJ~y n ed to US'1e hi .. UNIX progr mn ets should I till includ - I' e b, however, :S,O' 1I1id their programs wil~ be more portable to other operating systems,

Pve se n prog"am' 'l[t3 eall f'IDp,en ,aDd pu the le'ttL1f' t in the' Dllcd_ WII,a.! dues t mean?'

The C standard- allow> additionalcharacter to appear in '~h, mode string, rovided that the'y follow .r,!. w"a,. b, or +,. Some corn . iler allow the usc of t toindie te rhat a fi~e i" to: b opened in l 'xl mode instead oj binary mode .. Of course, text mode is the default anyway, S,C! t adds nothing, Wbenever po sible, r ~ be 1 to ,av. id t1'" ;D: t and other nonpectable features.

WI-' ~ot - er to IC' f'clo:ss '10 ~Io- 18 file'? h,D"" i'l 'true _ba,t _.- _, open file IBrII! c'iole; .automatiealh when apm ria temioa,t. ;1;' [p .. , 5' , '5]

Q&A 579

A: That': u ·U:all',' true, but 11. t if the pro ram calls aboxt; to terminat .ven when

abort. ~umtltio~ .2&.2 abort isn't used tlt U' h. there s still g d r I SR", to call ft]lo,se Fir t, it reduces the Dum" of op n 'fil· s, 10 aer uing. ' ... t- In, limit th ~ number of fil . that a _pro,gram m :'1 h v _- fI at t11. . anile tim, ': l~ _ pr grams may bump in'[ thi limit Th m.8.1Cr FOPEN_MAX, defined in ,<stdio. h:> specifies the minimum number ,~.l files [hat the impleme ntation guarante :, can be open simul an, usly .. 1 Second lb, program bee mes easi sr t under t nd an - modif ;, by I .• king fo th lei n 0_ fc.l oae. it i easiei flf the reader to del: -,[tuin_ the' point Hl which a file i 11· long r in use, Third th re - the is ue 10 . ail ,ty .. 1- sing ,3 file ensure [hal iteontenn and diT-ect'-I"_ l.en', · ue up'd~ ted pr p -rl' ;, if rh program " b. uld era h Ialer at I a l the fi] ~, il l b in t, ct.

Q.' I m_ rl_~n,g, a pTOr-: ram tl ~t ' ~ii_l prompl tl e ---~r to lent .. a, me Dame. ow II ng', honld I make the' eharaeter rra tlia,1 . ~11 .. ore 'Ib'- fil name?1 [PII 546]

A: . hall depend ,.n our - I rating", . tern. P' uumat t t ~ .. '. ,U . an [J,I. th, ma,-['.

F'ILENAMB_MAX I,_,tid in, <stdiQ,,,h> pecify tbe ize f U]Je array .. FILEN~E ~M1\X i I 'the length of ,I r ring thai will hold the lon st 61 name that the implementati n guarantees can b. 'p ned,

Q~:-,Bn fflush J11ush,BIr am tha '"r~_'. [p, ,54-]1

A,'~ According [0 Hie C standard, the IjJect fflush ~~ defined for '., scream

that (a) 'W UP'--D' d for output.r r (bj wa o ene for updetin an I whos la t oper~ ti 'I~ ""j n" a r . d. In . U . tb r c· .. 1'.·. the I ffect of calling fflush i ' undefined. h .. n fflu·s,h I, pa I.' cd I, HUU pointer it flushes all str _ m that sati:.fy either (a) or (b),

'~b feadin, nd 11· . -"tiog7

0,: CaD 'fh _' fo'rmat ·s:trlng! iD a eall of' " .. p:rin~f II , .... cBcanf b

A:: . ure: itcan . my expres .. ion oftype chaz >. Thi propertj makes the u"print'f

,8J11. .., .. 8 canf functions r ':ven m.· Ire versatile than W.:c' v bad rea~ 'on to ' n - pect, n-

sider the following 1- I ',i. lc examph from KJ rnlghan "lnLl Rit lUI_ s The C Pr(J81~aFn llting Langu; ge, wll L _1 prinu a pro ram ,~ '_ mmand-Iin an - urn nts, eparan by

paces:

while (- -arlgc :> 0)

printf ((arg'c ~ 1) ? II ts n : II %s *11 I *++argv) i

The t: rmat strin Q is. the expr -§,:,i n (arigci > 1) ? ~I % s n .. UI t Sill,,' hich e· alus " [0 n%s U for all command-line ar' urn 'nit bu lb, last

Whi ·'b Ub,r __ r- 'function I ·tb, . _Rd, ... '~m iDdi~< or? [p, ,5'-'1_1

A; Calling reWl.nd clears b th i -diet'" tors -, deet openir g or reopen in, th stream, Cal ina unqet;c, fse,e]~ . ,- f,set:pos -I ars just (h .. _' nd-of-fil indlc ' r,

taan clearerr clear a stream's I.,rro.r RO.d

'Q*:_lIn-" g'. feot to " ork~ it se c -~, .te return J:' ·[0_

1 doin, oog II [p, _ .. -5]

at ." ,d-of .. file'~

'. " I

~ quirl t he En -I, '"f

____ I, typed" I I, ,--

, . , .

feof 'ill oj eturn ~ n nzer v. lue when a pre iou read' 'ra in h~ _ - ailed:

OD an' u e 'e6f to' check f ir end-ef- I, b,-fore" U mptiug t re ',dll' Instead, you sh uld first s tterrrpt r read, then check til r turn value from the input function, If the return al ue indicates th '( the IQ1P' ranon ill .cessful, - ,'U c n then use

feof [, de t, - rmin wh the r [11 . faih re w_ _ ue 0 len -0 - ile, In (} -b rrd it.

best no '[0 thin I f c ,lling eo f ., a w,_ ~ - dete: t I nd- 'f-file. ' - I tead think 01 it a u \ a,Y ~- I oonfirm that lend- f-file \ a' th r eason for tile failure of 3 !lcad opers ~ tion.

A:

I I, : - til ,I:fl- ,., 1_ i -- IC~D, 0'- m ed PIU tiC a d

get,c in addition to fnnetie " named f, -tut,c ud fget,cli '_~'I~OI din 0"'lion 1,111, there Ire airea,d two v r ~o - of pu'tc and getlc II macro and a

fu -lion .. If' ~-'. - n eed I -,' nulnefun -Ii, D mstead -:'( - macro, e Ican;pos, 'ne

Pluto nr ,ge,·a -: netl m b nnde 'iu, mac'~, -, b d fputc an ~

fg'ete e-,-;;t' [p, --6' ~

n PM' r to standardization . - had n ' rule ' hat th e re be a true unetion [0 back up each parameterized macro in the library. put;c and qe.t.c weretradin uall implemented nl u' macro ,~ fputc and fg'etc wier implement d

nlv s fun ti n. ,.,

:;~Q: bill' wr 0 I \vilb,lori'n'_ the retnrn _Iu,_ of fgletc" gate i 'or ge'tchs,r in

h II I? I d - -It h tln 'h II bl - I~I- t '~o old

t C !il.r ' ,~; - Ill, I. " 011 ;e' _ 0 '[" "a C'I,a,E v' .0" e a,:BJLD, !L::,I' C',,' - ~

"r th _,_D' ~ answer, [p. SIlO]

There are t cas - " in ~ 11i h this te t can gi the' "008 resul ~ m tke the' _IO~-

[ "in'gdi ussion concrete, IOU R' sum, ~" 0 '.'_ omplem n arithm tic.

Plrst, i,l ppose that char is ,J] unsigned type, (Recall that sorn compilers

eat char a~ s a I igned type' bur other , tn 'i it it ,,: an un ign ~d type. No' uPI' < that gate r turn EOE - hi 11 we " OIr· in a cha'r '\ ariabl named oh, n BOF r pr sents -~ I it _~ pi al vahn , ch will en up'" ilh rbe alu '·5. I, n paring cb I' an un: igned ' b ,. cter) with EOIF (3 ; igned Integ r) requir _' C' ··10, erring ch to it igned inti ger (_55 inthis case). '_ te compari on against H,OF fails" since ·55 i , .. not equal t -1~

,I U - that ohaz i "I sign nsi er 'hu hap D I il

gate r n'· ,~ byte containing the valu ..;.. I from u binary stream. I ,coring 255 in th - eh variable giv'e" il the value -1" in, ch is signed character. Te tjn,~ , hether ch i~' qual to EOF' \vHI (erroueously) give '. true . sult,

I J p:l}ogra - .•

A: -'_I you 've netic -d the getc:,,, fgete, and qe tcha '" fun I ti ~1'L, re buffered: dl~'Y

don' t, t ret inpu un il .h,e u, er has ore ' ec 'h, sn er key, In 0' d r to read h racters : " th y're entere 1- hi, his important ur ., me kind 1- program ,au" 11 need { II ,e a non-' n ard Ii brar hal"- tailfWd to our operating sy stern, In UNIX~ for example, tile curs,es library often provider tho, cap;,lbllity"

Q: Wben. _ "m reading: user' inpn't- bow can I '"w.p all ehar eters lef OB the enrren iuput line?1

A': One possibility·'. lUll write a smlaU: functientbat reads and 19~1IOl'." all chr raeters B,P to (and including) the .. Irst new-line character:

Q

I !

II'

A·'

"'

Q

ti

Ii

A· ,~

iii

}

Another possibility tsto as~, s,eanf [10 skip all character up' to thl· fir ,'[ n _wline character:

acanf will read al _. charac IEel tllJP [,0 tb ' first new-line ,haF,acte[ bn:[ nor srore th un an,ywhere (th,e * indicate assigmnent suppression), The on])! 'problem 'with using scanf ms, that it Ie ive , [hie new-line character unread.so you, ma:y have 'tOI discard it separately,

Wb'jatever you do"don'~'t call the f f Luah function:

f'flush (' st.din) ;

Although I, om Implementatiom allow the u e 0 f flu,sh~o 1;1 flush' unread input, it's 0:10'£ a. gOld idel to ,as II me that all do, JE flush i _I d _ sign ed :il, flu. ~b outpet streamsithe C standard states that its effect oln LO' ~IU.rtrleam', i undefined,

Why is lilt D,ot '. ,good. i,dea 10 DS"~-' f'r'le,ad and: f'wri,tSI 'wl~t~, t_",~l,s'tr~'J ,m '1 [p~ 5,71]

One ditficulty is that, un '[ .. ome operating sy items, the new ... line character becomes 1ft pair of characters when written to a text file (see Section .... 2,.1 for details). We must take thi expansion into account, or else we're Ute!y to 10 ,·'e track of our data, For example, if w'e tl~ e f·wri.t,e ~Ol wri 16 blocl IO! 80 character '" some of the block may end up IOCtllpying more 'til:n ,8,0 bytes in the file beeau e of D wline characters that were expanded,

Wll'Sfle 'there t;, ,0 S!.'~: ,of 6Ie-po:i,_jlo,niD;M;, 'func'tioD' (fliluaik!ft1el,1 and f'set'PQslfge':~·'PQ's)? . ," 'o'Dldo"'£ one set 'be eD,o~gb?' [p, 5:7;4

f s @.'I2k and f t; e 11 ha:v, be n pan of 'til C l"br y for eons, The')' have on ' Idr.a:wback" though: tbley 13 sume that a [tl_ position wi.D Eh in a Lonq .int value, Since l,ong i:nt is, tYP'lc,aUy a 3,2~blt type, tills mean' that fse'El:k,and ftel1 may net work wl'tb file. containing more _h,an 2 I :7 4:81-6'~ 7' bytes,. In recognition of 'this problem, f set.pos and, fgetp'oe, 'were added' 0 <.::stdio. h» when C8i9 wa , created. Thee functions aren't required to treat file POSi'IJOiB 3' number so they re no" subject UOI the lon.g int restriction. But don't g··u:U1JC tbat you have to' use fS"e'tp",oBI "and fg.e·tp,os~ if your implementation supports I· 6!4~bit lOID:g int type fS,@'Bk. and f't,,@ll are fine even for very larg files.

Q'= 'Wby doeID"t· tb:ls, dUlptte ' distnss,',c~-eeD control: mO--~DI "_h-~' ell_" ,I; chan,giul the cololrs 10 characie-s OD tile !uee~D -I' aD,d so' no?!

A: C provides B[J standard functions, for icreen :_ontrol. The C '. tandard addre . es only issue» that C~1U1 reasonably be standardized across a wide ,~angle of computers and operating systems; SCL'icerll control 1l8, outside Jus realm, The customary w,ay to solve this problem hl UNIX" is 'LOI use the cu_r,ses, library" which supper 'I screen eontrol in a terminal-independent m',!]) nee.

Simi Lat"ly I U1Cr'f! are no '. ta_Dda~rd, functions for building ~pro'gram_s w hh a.graphicalli US_'f interface, However, you can most likely U':C CI function calls. to access Idle 'wiod.owingAPI (application programming interface) for YOU1 operating system.

J. Indicate whether each of (he fo~]owing files ismor ~.ily lu contain text data or binary data:

(a)1 A HIe of object code predaced by a C Icompacr (b) A program listing produced by.a C compiler

(,e) AJrn, email message sent lliOm O' .• lle ,COI1llrpU£er to Mother(d) A nle conullininl a Imphk~:s image

Secli~on

lodicilte which mente s:b:iog is most UkeJly '[0 be aassed to f'op,ec In eo! 'b of 11· tb]h1rwing s.iruadon :

(I) A database ,manaFln.ent syl~enl opens, ,3 fine containlng records 'to be updl,~ed ..

(b) Amail program opens a rue ofsaved messages S;,O tbal jl can add additi Dar] messages U]I the I nd.

(IC') A graphic I program ,op._: III ,Ell file oontaining .1. picture to be djspta,yed on 'tbe screen.

(d). . 'n '~J'perati:l1g system command interpreter opens a "shell script" (or "batch file") eentUl1Ilng commands to be executed,

31" Find the error in the 1'~o110'win,B pregram rt,agme'O\ and ,sbow bow 'ItO' fix it FILE *'fp;

if (' fp = f open I( .f;i 1 ename IIII r II )} {

read charecters u n1 U ,flnd'",ojf fil.e

}

fcl'Qs,e (fp,) ;

CJ 4. Sbow how ,eaen 101 - [be' fonowing number wiD 10 k if displayed by prin·tf with % --- 0'12 ~ 5119 1.1 the eonversion s'p,ec.itm:c;"lioll:

.ca) 813~73'6]

(bt) 29'748.61607 (c) ~ (151493 234 .. 0 (d) U.00002352,:iS

5, Is there any differenc between 'the pri:ntf conversion specifications " .. 4,d and % 04,0''1 r S(JI~ explain wha,tit is ..

583

*;6. Write a call ofp r in ct· that prints 1 widg'let.

'if the w'i,dgetvmable (of type int) has, '~e value L~ and ,'1 widget,s,

otherwise where 11 is the value of wi age t. '¥ou are Dot BUowed [0 use 'the .i f statement or MY other statement: 'the answer must be a, 'single call ofpri:n:tf.

*1. SUPPO'8 that. 'we call aoanf B:S follow :

n == scanf I( ~~ %'d%;ftd II, &i, &x" &d);

(L, j ~ and n are Lnt, variables and x i a f 110a t va'dil,l .) A, , U'Mina . hat th' jnl' - ut .. tream contains the characters SlU1WQ· live the values ,of i~ j I' n, and x after the ca I I", In addition, indicate which characters were consumed by the call,

(a) 10,.20,.3ICllg

(b) (c) I~dl)

1 ~,."1 n III 3 10C'

.~U '~JliU i·

n 1.10' 'i') I. O· ]-'!C'

~ ~ - [Ii [6. ",-. I!!I -,'

1- .,. ')0

!!!! !!!! ,iICi !!!!.

• :8,. In previous chapters, we've used the scan! formal string. n ~c u 'whel1 we wanted Ito ski,P white-space cheraeters ,and read a nonblank character. Some pn)grammers usa II t.ls H instead, Are the 'two techniques ·e'qn.iva],eo't11 aot, wlla.t are the dtE =;erenoe' .""

9 ~ W'biGh one of the following calls Is I~O~ II. valid WHJ In' reading one character Hom the standard input stream J]

(a) g'et ch ( )

(b) 91~ t char' ( )

(c) get e (' B tdin)1

(d) fge t.c t( ,s:t:di,n')

II 10. Thef copy. c program bas .one minot D.a.,w:, it doe,Still ~ cheek for errors as if IS wr.1ting ~o the de:stm,adoJil file, E[[IO[s, during wri;.ting are rare buc do occa~non,IU)' eccur (the' ldisk :mi,gb't become full, for example), Sho'w bOlw to ,add tIle missing .. rrer cheek tOI the pIogr,~ :111'- suming ma't we want it to display ,I messag and terminate Unmedi,I'tely if an error (] ecurs,

m I, 'The foUowing loop appears in the fe~oPi.' e 11Iogr,am: while (,I{ch ;;;; gate (en:l"urc'e_fp))1 1:= .EOF) putc(ch, dest_fp);

SUPPOSiC [bat we neglected to put peremheses IrrQUIild ,[!h ~ ge i' c (8cur'cle~fp) : while' ('c,h -= 'g'e:tc. t s:ourGe_fpl' J;;; EOF)

put;c ('chi Idest=fp,)I,;'

Wou..d the program compile w~lbout 3D. HUor? If se w~hat would the program do, 'when m.'t"s run?

.12.. Findthe error in the f01ijowillg functien and sbow haw tOI fix it, tnt ,countJ)eri,ods (eonsr; char *fil-lll!.naJ(le)

,{

FI.LE *fp; int ,n = ();

if ((fp = fo'pen(filenamle', nrllQ') J != NULLJ { 'whi lie (f'ge'te, l~fplJ ~ ~ E,OF}

if (fgetc(fp) ;~ ~. I)

n++;

fc.los·H (fp') I

]

re,l-u¥n n:

. I".... _ ~ , "

13. Wd~e the foJ'1J.ow'in,g functh.ln:,

i:nt liu,e_length (clo;nat ehar' *fi.lename, int n) ;

The functien should renen '[he ]Itngtb of H.ne n ln the text ,6 le whose nam _' i filename (,ass:lll1l~tlg thatthe i u:~,t ~ i ne i, the file ii , U ne l), If me line doesn't exj..l,tblf:' function should 'return O.

Se' nl'ion 'Q2·'1 5-'

~ .,'j~' I I,~, ' .. [~'·~I.,L.~I

I' 14. hll) Wrille your uwn. version ofthe ,fgNets fuoction. Ma.ke' i.t behave a's, much like the real fgets function aspossible; 'in p'Mti1cular make' sure that jt ball the pmper retnm 'value. 170 a.vt(lid ecnflicts with the standard l.ib:m:ary I dO,I)'lt name your fUDction fg'e,ts,

(b) Wd.'lIC your own version of rputs-, following the same rules as m p',art (a) ..

:Section 22,,'7' • 15"

W:rj'te ealls of f:seH~!k thill! perforra the foU;owhlg tlhe~PQ,sitjQJning ope"ra:ti-ons. Ion ,a, biuazy file wbose' data ts arranged in 164-byte "records, - . 51,. fp a the file pointer in each CD,Sec<

(a) Move ro the begirullb,'g 01_ reeord D"" (Assume ilia.', 'be first record in. [be 'file is, record l(l,J (b) Move t!QI the beginning 01 the bu~,t record in the fil¢.

(c) Move. forward one record,

(d.) Move bac'kw.ard ItW'OI record .. 1

1,6. Assume thsts tr :i' ;!L sldng tba:~ contains ,iB! "sale ntnk1'. immediately preceded by the i

symbol (other characters m,ay precede the -# il.odlor :fonow the sales rank), A sales rank is ,I series of decimal digits pos,sitdy containing commas. such ,as the following examples:

,SH39

24, 675,

I, 162, 1620'

Write a, c8I~ of ascanf tbat 'extracts tn_c sales rank (btu nO'l th,e # symb(]I~)1 and storesit in I string variable named ,~HaleB zank,

e ,.."..

~ !' Extend the canopen ,. e "p:rOgr,ID] of Se~tlon 22.2 so that the user may I,m any number of file names on the command Ijjne:~

canopen foo bar' :b'az

The program should prirIJ'l a separate can b'e ope.neid or can I' t be opened message far each file Have the program terminate with sb.llllIm EX .. IT _..PAI1.l.UR.E lf lone or mOJie of the files can't be opened.

al 2. Write a program that converts ,Illl letters in a file to upper case, (Cbu,lcte:rs other than Jet~ -rs shouldn't be changed.) The pfogra- ·'hould obtain the' file aame from the command line and write its output to ,6 t dIQU.t.

585

'r1t a pmgr m named feat hat' von atenate any DU:r of files b writing th, m '0 c,t " dard outpu OJ] - aft, r th ~ tiler with no br , I, betw =u n fil .' or exam ~, the' Jlwm'

command I ill dis liar he fil " f 1 ~ 'C ~ f 2 c ' d f3 .' c In th ~ sere n:

=cat fl.c f2~e f3~c

fca t shouk i' u an err 11.1 ~' I, ,I if I , ~ y , au l be open ed, Hint: "line' it ha- nl, me

than ' 'ne 61'e open at a 'tim ,- f,cat needs onl lin I 'I] ointer v ri: bl '~ Once it, in-

i shed witlrl 111_" f oa t can 11: :_ rhe aITI_ sri, ble when it opens the n extfile.

• 4. (a) Write a. program thatcc unf the number 0' characters I in a 'te t file.

b Write II program that cc unu the nt m er I "~ sequence of non-whi e-,I, _ ,a'ce ch I cter . I

:_'I Write I program that c un - the number I f Iines in a t ',I fil .

Have each pro,gram obtain the file name from th ccmmaml line.

s.

I 6"

, I ..

#include .c' S dd,o . h> ~ '" .,int main (vo,id,) " " { .

pzLnt f I(

III To ,(""1 I - ~

- - \.." f or

not; to c: -hat is 'th e quas t; i on

\n·'IU) ",'

iii _ ,~. ~

re'turn 0; ,.

. }

hie xor ~ c prograrn of Section "CO .. l refuse t .enerypt ~Iytle that-in ori in l or lencryptl_d

-OfID-ate COD,mo~ charaet r ,,"WI an no rei - ov [hi r _ riction, ·'dif~, tbe program ','_ that tb .name I f tb inpu and utput file ar d-line gum - nts, Op en b tb fil 1- ill binary mode, and remove the te" ha I, he' "' whe the the' original and en rypted characters ar!" printing character .'. '.

- 1 rit a p[1o,gram that diplay., the content a ytes - d. . -h~1 a I Ii- ~, H ave Itb U" ·f'

'·-ec·', the 1'1 . D me en th ·ommand lin" s, ere w - -_ th out 'ut in I, ok like when 'he pr gram ~ U led La display th pun" e fil o Section 2.,1:

Of,fs,et B:y1te,s Charac.ters

~----- ----------------------------- ~---------

o 10 20 30 40 s·n

60 70 80 90

100 110,

2,3 69 6& 63 61C 750 6,4 6S .20 3C'
73 74 '64 69' 6F 2E 68. 3,E OD a,A
' I ,.
OD' OA 69' 16E 74 20 6D 61 69 6E
2'8 76 6P' 6:9' 64 29, 00 OA, 7B OD'
I' ,
OA 20 2,0 70 '7,2 ,69 6E 74 616 28,
,22 54 c'p' 20 43 2C 20 6F 72 201
6E 16F 74 20 74 '6F 20 4 , 3A 201
I
74 6,8 61 741 20 69 73, 2,0 7,- 6B
65 20 71 75 65 73 '14 69 6F' 6E:
' .
2B 5C 62: ,22: 2,9 3B on O,A, 20 2:0
, ~
72 65 74 75 72 iSH 20 30 3B 001
OA 7D ach Iine shows ~O byte I ", -11 til tile" . hexadeci I al Dum rs and , . haract T,. Th

Dum- - in the IO'if,s,et column indican ' [be P ',iUOD within the 1]- '_ th ' _1,_-;'11: by' _n the line, IOID'ly printiru character (as determhl d y the isprin,t function] are display d: other character are showns periods, Note that the appea_-ancle of it text de may vary dep ,'Dd~na on the characte I. "f and th, p rating I, I uem, Tb I ample rbov ,: sumes tha

pun ~ c ., a indos '.' fil ,,101 00' and OA b_ . _' I th carria ' -return and line- e d

I hare ,·ten;) 1,,_ IP'·~ :CIt the end of each line, Him: 8, ~ sure t onen the file in 1m rb II mod .

7., Of the many techniques fo. compressing tbe cements , if, . flle one of the simplest and fast ... est L kn,own D, - rO.I_1,·,1:6 -'I" e ClodiRr,~, This technique I ompresse a file by renlacias s qU'DIC _ _ of identical byte b ' pair . b: .~. es: a repeti In count o~]·" d b a byte t b

re P : a ed. For amplev sup se th t the . I, to be c enpre ',I d begin ith the f01 lo in-

.; 'qll. '0" e of byltc, , bown in he ' adecimal :'

46 6F 6F 20 62 61 72 21 21 21 20 20 20 20 20 The eompre I d file v ill contain 111 felloe ing bytes:

01 46 02 6F a1 20 Q1 62 Dl 61 01 72 03 21 05 20

ROll-lengtb ,encoding work_.'swe]~ it 1'lIle ori,gin'al file contains M13.l1} Long .!equ'ences of Idemica'~ byres. In the worst case (3 file w]tb no repeated b:,tes)., ran-length encoding ean acuU.ll1y dJ,Qu'ble the ~.leng[ll of 'the file,

(al WrilLe ill, program named e~'ompr,ess_file thm uses nm-leugd1II!Dcoding to c ·lmpll·- :~ ,I file, lb IUn ~OIIlq;pX',e,s~s_ft.la,t w'e'd use' a command ,of the form

cornp'res s,_ f i 1.,81' ()"i/l'inal-ji,t'ftJ

caml;;n:es s~f i lie will wrj'metbe compressed version g,f ,tfJ,"igi"~Ql'-JI', '111'rfJ,rigitlQl-.fU,~, r 1 e . For example, the comm,lBlDd

cQ,mpre.5ua.~fille fac,. txt

win cause campress,_f ile 1,.1 \'D1te a compressed version of feo., 't,xt.to a file named f'oo., t.xt., z Le, Hint: The program described in Programming Project 6. could be useful for debu81ing'i

I b) Write a program named unrC~lamprerssl_file dULL reverses th compression performed by the 'compr,eBs~file progr,am", 'T,I]]e uru::lomp,r'B.ss_f·ilB conunand . ill have the ftOitm

uneompr'es B_1 i lie cOlr:lpre's··ed-jil,t!

IC(J,nlp,re!~'f'f:d'1ile' should hBV'~ [he extensirm ~cl a, For example, the command uncompress_. f.il'8: foo '" t.xt., rle

'wi]] cause unlo,omp.ress_fi~e [0. open [he rUle ICC ~ txt ~ r'le and write an uncompries sed, ver:si'on of its Ic~ontenr-- tof'oc .,EX,t. 'unco,'mpre,BBii=iiOf11e should msp'layao error message if its command-Iine atg,llm,e'llt doesn't lend with the. rle extension.

8. Mlodify the invl91n'tory .c p,.ogr3nll of Section 1 '6. 3 by addin,K two new operations:

.1 Save 'the database in a" speclfled file, .

• 1 Load '(he database from. a speclfied file.

Use 'the cedes d (dump) and r (restore) Jtes:~p.ecti\l'ely, to repre~en,~ these eperarien .. The interaction 'with the usershould have the. foUowih,g appearance:

18nter operataon code: ,2

,En,te.r name of outiput, filii!: inventory" dart

E-nte,r Qlperaian eode: .r

E.nt,er name of input. til,8; inveNtory~ldat

Hint: Use fwri t.e to writethe array comminmg the parts to binary rde. Use fread (0

restore 'the array by reading it from a file, .

• I~t Wri'~e a program that merges two tiles containing Piatt records stored by lbe inventory .. c program I( see Programm iag Prlojec'l 8.). A st;llm' that "[be records in each file ar~ slotted by part number, land that we want Ih,,~' resulting flle to' be sor£edl a's well. _f both files have a part .. ~itb the same number, combine the quantities ·toted to the recerds. I(As ~" consistency ,check, have the program compare the p.m names and prmt an error message ifthey don t m,atcb.) Have the program cb tain the names, of the; input files and the merged file 'from the command line ..

*10".. .M.odify the inventory.:?: .. e pnlgmm, of Section 17.5 by adding the d (dump) and r (restore) operations described in Pro,gra.nnni.Dg Pn}jec(~ ;: ,_ Since me part structures :Del1 [ stored in an WT,IY., the d oper,uj,ob, C:;m"L save themall h,Y a single call of f'writ,e'.los·te,ad~ it will need to visit each nlode 'in U.1C linked list, 'writing tbe part number~ 'pm name, ana qlUa:o~

,~ty n h rod minates, I

~ _ '- , ' tb.c- next p, ~_J~ -:rom a fit . Idl- r . p era I n

nn't be valid ne the --c- ~ ill rebuild h· u

1 I, W'rite_ pro:- ram that re de a date ~ m ih command lin,€: an' display it in th . foUa'. in!

mn;

. .

Septe'mbler - 3 I 2010

',J, the user t, e'er the 2JJte as eitl er 9'-13~20110 . c 9/13/20 0;;,' u may assume tba:1 ther iii, IfJ10 .pace:, 10 the dat i Print an error me I ,g' ~- _ tb~ date d _';'H 1i,3[V '0l1, f the pecific:d forms .. ,Hint' Use ss,eanf to extract the month day .. ". nd year romth commandr

me argnm enr,

--di_. - .~( 'ammin, Project 2 ' I' b. er I

from a Hie and. displ y. 'h _ da a in . .- lu - -. i a,· 'h lim rorm:

he program _c '_ d~ a erie I·· 'it m'·, the file "Ii U ba- e th _- followin

item, '" ic ~ ,'Uft ldd/ y~ 1\,. ,

For example ~. U ',: ',' .' e' ha ,h fi lie ............. ' .... e _,JI,dI.LI'" tb

5,8,3" 13, '~I 5" 10/24/2'005

3912,599~9gt7/27/200B

he out u.t 0 the P" ,.' ram ,h uld hs '_ the -IUO-,' in pean __ ce:

Ite'm ani t .. rrohas

... ..

583 3912

Pric,e

$, 1.],,50 $ 599 .. 99

Date 10/24/2005 7/2" /20108

Ha e lb· program obtain the file nam rom; , - e comm n - line,.

I ',. -,- h ~ the program ,II~ taln dp. 11- a-d

arrival .; . ail named flig.hts ' dat BI! h line '" f the file in conte in d par-

ture time ~ollowed by an arri . 31 time wid- . ne lOr 'rna 'p'acer, . - 'para,tio,g the -wo" imes , . ill b ~pr,: ed U·,'· n,~ th - 24.-bour cl ek, _ or exam I 'beres 'h·' : - 1 ig h t s '. d '. \ h 100 11k i' it I ontained th flight in I rrm I' ~I [II li·t d. in the I ri gina) P' ~e .-l:

8,:OiQ 10:.16

91-4i] 11;;;15-'

I'll, I .1 - [6

11.:~91 13;~31 1,2 : 4 7 151: 1010 14;;;00 16:08,

15, ! 4 5 1" ~ 5 5 1.91 : 00 21: 210 21 : 45 23: S8,

1- .

Modify PJO grammin I Proj t 5' rom r h" pter 1.{1 I hal mer tbe name ,of a file I~. ntaining the me _ ze .1

Ent,e.r name ,of ~ il,s Co Die encrypt.ed: mEBs.age '. txt En'ter shift ,amou'll't (1-2'5)1: 3

p ompts th u er ~D

Tbe program then write _, the CI}IC ~ pted l11k .. ' . ',. e [0 a ru -. ith th _ ·ame. namextension t ',f ",lane,. n tbi:, Ie· un 1 , the .e igiu 0:--7 e ~ 'm~s,B,age ~ txt, __ - th_ ,:ncryp~d me . age wHl be storec in.' e named message.·txt eric. Tb re n limit on the size of the le 10 be __ ryptec o 11 the 1 ength 01 ' ch line in th .file,

1 5. .,- - odif. lb,_ j ust.i fy prt1,p"am 'Of, ec · 0' l' ,.3, 0' tha it read" fro m one lex file· d wriI' to another; H~[ e the pr 2fan1 obtain . he D' ,-, eo' th ~l .' - : m b -, I ~ mmand lin ..

J 6. Modify 01' fcop'y. C prqgl,Bill of Section 22.4 so thaL it, U' es -frlead In fwrft.e to cOP)'

Itb tile in hi cks c -_ "~ 12 :,~ I' .. (Til. la -l bJI k mnt t te .. ' -r than S l~ b '~I:_ I, .• " coarse, I

17~ Wrh~ a program tba:r reads a series of phone numb Q from JI file ;W1d dj "play" tbem in a

tan: - am format, I ill' h line f ih=' fil v ill '1:1: Dam. log) phone DUJll-> hu ttl, numb tl13-_' -c in arie 'f fermats. You may assume th,: L each line contains l I di,gi , po lbly llli led, with other charac _ ,', (whi h shoeld be Ignored) For exampla sup _Ole rb3lJ[ tbede r ontaies lb follo . in u lin~ :

4,04,.817 _ 6900

( 2a 5 ') 16 BE' -1 7 716 ]12 -7 _16-,6ICOO

877 2:75 5'~'7'3 61734~,420ICI

'T11t! omputof the ·ro.~'m ~houl,d bay' the rellowing appee ranee: (,404) iB17-090'O

(.2,1.5) 6,86-17'16

t.312) '].4,6-.6000

1(' 877' 275-52,73

(51?) 3_3--'200

, -a: ,e the p~g" _m " b ain lh - ~ I 'ill I - from the cmmand nne.

tH, Wr'it a program bat read" Integers fromatext filewhos ,.,. 'name is given as a command-line ·argument Each Iine "/' th rfil' '1n'_' - IC' nl,ain an number '0.[ rnte'g,er' On It! !11l,:' n nC~)1 .' epar'al sd by I:' ,,' r rm - -, . pac Ii Ha:\t. the program rdJ- pla 01_ tal: g I,l number in me file the smal lest num ber, , nd th _' median (the number closest to the middle L the iDJ~ ~" en W' re :olrt d). IT the file c. rntm.in', an even number- o~ intege ~ there ~n b 't " number; in the

middle: the program should displa . their averag rounded downll~ou 1m, ,.' um, lb.' I~h

rn conrains nc more '[b"' n I o~noo integers, ,HiJl'. Store 'tbe inaeger· m an ,DITa;y and then sort tb. ,a[fay~

lr~l. 1(1a) Write'ii. program mat Iconvert- a Wmdows FeXl file E'O a '~, r a discussion of the cliffe, nces b t. ;-,;_D''indo,- Ian

b) rite II, program that cenve .

In __ eh ase ba, e the rogram ob't in f '. name" 01 b· rtbfiles from the '. '. mmand line. Hinn I ,p .. n the in ut file in 'll'rb'l'l mode and the om nu file ill IIwb,lf mode.

You might also like