Tải bản đầy đủ - 0 (trang)
Chapter 8. Character Input/Output and Input Validation

Chapter 8. Character Input/Output and Input Validation

Tải bản đầy đủ - 0trang

mustworkinawidevarietyofcomputerenvironments,they

seldomtakeadvantageoffeaturespeculiartoaparticular

system.Therefore,manyCvendorssupplyadditionalI/O

functionsthatdomakeuseofspecialfeatures,suchastheIntel

microprocessorI/OportsortheMacintoshROMroutines.Other

functionsorfamiliesoffunctionstapintoparticularoperating

systemsthatsupport,forexample,specificgraphicalinterfaces,

suchasthoseprovidedbyWindowsorMacintoshOS.These

specialized,nonstandardfunctionsenableyoutowrite

programsthatuseaparticularcomputermoreeffectively.

Unfortunately,theyoftencan'tbeusedonothercomputer

systems.Consequently,we'llconcentrateonthestandardI/O

functionsavailableonallsystems,becausetheyenableyouto

writeportableprogramsthatcanbemovedeasilyfromone

systemtoanother.Theyalsogeneralizetoprogramsusingfiles

forinputandoutput.

Oneimportanttaskmanyprogramsfaceisthatofvalidating

input;thatis,determiningwhethertheuserhasenteredinput

thatmatchestheexpectationsofaprogram.Thischapter

illustratessomeoftheproblemsandsolutionsassociatedwith

inputvalidation.



Single-CharacterI/O:getchar()andputchar()

AsyousawinChapter7,"CControlStatements:Branchingand

Jumps,"getchar()andputchar()performinputandoutput

onecharacteratatime.Thatmethodmightstrikeyouasa

rathersillywayofdoingthings.Afterall,youcaneasilyread

groupingslargerthanasinglecharacter,butthismethoddoes

suitthecapabilityofacomputer.Furthermore,thisapproachis

theheartofmostprogramsthatdealwithtextthatis,with

ordinarywords.Toremindyourselfofhowthesefunctionswork,

examineListing8.1,averysimpleexample.Allitdoesisfetch

charactersfromkeyboardinputandsendthemtothescreen.

Thisprocessiscalledechoingtheinput.Itusesawhileloop

thatterminateswhenthe#characterisencountered.



Listing8.1.Theecho.cProgram



/*echo.c--repeatsinput*/

#include

intmain(void)

{

charch;



while((ch=getchar())!='#')

putchar(ch);



return0;

}



ANSICassociatesthestdio.hheaderfilewithusing

getchar()andputchar(),whichiswhywehaveincludedthat

fileintheprogram.(Typically,getchar()andputchar()are

nottruefunctions,butaredefinedusingpreprocessormacros,

atopicwe'llcoverinChapter16,"TheCPreprocessorandtheC

Library.")Usingthisprogramproducesexchangeslikethis:



Hello,there.Iwould[enter]

Hello,there.Iwould

likea#3bagofpotatoes.[enter]

likea



Afterwatchingthisprogramrun,youmightwonderwhyyou

musttypeawholelinebeforetheinputisechoed.Youmight

alsowonderifthereisabetterwaytoterminateinput.Usinga



particularcharacter,suchas#,toterminateinputpreventsyou

fromusingthatcharacterinthetext.Toanswerthese

questions,let'slookathowCprogramshandlekeyboardinput.

Inparticular,let'sexaminebufferingandtheconceptofa

standardinputfile.



Buffers

Whenyourunthepreviousprogramonsomesystems,thetext

youinputisechoedimmediately.Thatis,asamplerunwould

looklikethis:



HHeelllloo,,tthheerree..IIwwoouulldd[enter]



lliikkeeaa#



Theprecedingbehavioristheexception.Onmostsystems,

nothinghappensuntilyoupressEnter,asinthefirstexample.

Theimmediateechoingofinputcharactersisaninstanceof

unbuffered(ordirect)input,meaningthatthecharactersyou

typeareimmediatelymadeavailabletothewaitingprogram.

Thedelayedechoing,ontheotherhand,illustratesbuffered

input,inwhichthecharactersyoutypearecollectedandstored

inanareaoftemporarystoragecalledabuffer.PressingEnter

causestheblockofcharactersyoutypedtobemadeavailable

toyourprogram.Figure8.1comparesthesetwokindsofinput.



Figure8.1.Bufferedversusunbufferedinput.



Whyhavebuffers?First,itislesstime-consumingtotransmit

severalcharactersasablockthantosendthemonebyone.

Second,ifyoumistype,youcanuseyourkeyboardcorrection

featurestofixyourmistake.WhenyoufinallypressEnter,you

cantransmitthecorrectedversion.

Unbufferedinput,ontheotherhand,isdesirableforsome

interactiveprograms.Inagame,forinstance,youwouldlike

eachcommandtotakeplaceassoonasyoupressakey.

Therefore,bothbufferedandunbufferedinputhavetheiruses.

Bufferingcomesintwovarieties:fullybufferedI/OandlinebufferedI/O.Forfullybufferedinput,thebufferisflushed(the

contentsaresenttotheirdestination)whenitisfull.Thiskind

ofbufferingusuallyoccurswithfileinput.Thebuffersize

dependsonthesystem,but512bytesand4096bytesare

commonvalues.Withline-bufferedI/O,thebufferisflushed

wheneveranewlinecharactershowsup.Keyboardinputis

normallylinebuffered,sothatpressingEnterflushesthebuffer.

Whichkindofinputdoyouhave:bufferedorunbuffered?ANSI



Cspecifiesthatinputshouldbebuffered,butK&Roriginallyleft

thechoiceopentothecompilerwriter.Youcanfindoutby

runningtheecho.cprogramandseeingwhichbehaviorresults.

ThereasonANSICsettledonbufferedinputasthestandardis

thatsomecomputerdesignsdon'tpermitunbufferedinput.If

yourparticularcomputerdoesallowunbufferedinput,most

likelyyourCcompileroffersunbufferedinputasanoption.

ManycompilersforIBMPCcompatibles,forexample,supplya

specialfamilyoffunctions,supportedbytheconio.hheader

file,forunbufferedinput.Thesefunctionsincludegetche()for

echoedunbufferedinputandgetch()forunechoedunbuffered

input.(Echoedinputmeansthecharacteryoutypeshows

onscreen,andunechoedinputmeansthekeystrokesdon't

show.)Unixsystemsuseadifferentapproach,forUnixitself

controlsbuffering.WithUnix,youusetheioctl()function

(partoftheUnixlibrarybutnotpartofstandardC)tospecify

thetypeofinputyouwant,andgetchar()behavesaccordingly.

InANSIC,thesetbuf()andsetvbuf()functions(seeChapter

13,"FileInput/Output")supplysomecontroloverbuffering,but

theinherentlimitationsofsomesystemscanrestrictthe

effectivenessofthesefunctions.Inshort,thereisnostandard

ANSIwayofinvokingunbufferedinput;themeansdependon

thecomputersystem.Inthisbook,withapologiestoour

unbufferedfriends,weassumeyouareusingbufferedinput.



TerminatingKeyboardInput

Theecho.cprogramhaltswhen#isentered,whichis

convenientaslongasyouexcludethatcharacterfromnormal

input.Asyou'veseen,however,#canshowupinnormalinput.

Ideally,you'dlikeaterminatingcharacterthatnormallydoes

notshowupintext.Suchacharacterwon'tpopupaccidentally

inthemiddleofsomeinput,stoppingtheprogrambeforeyou

wantittostop.Chasananswertothisneed,but,to

understandit,youneedtoknowhowChandlesfiles.



Files,Streams,andKeyboardInput

Afileisanareaofmemoryinwhichinformationisstored.

Normally,afileiskeptinsomesortofpermanentmemory,such

asafloppydisk,aharddisk,oratape.Youaredoubtlessaware

oftheimportanceoffilestocomputersystems.Forexample,

yourCprogramsarekeptinfiles,andtheprogramsusedto

compileyourprogramsarekeptinfiles.Thislastexample

pointsoutthatsomeprogramsneedtobeabletoaccess

particularfiles.Whenyoucompileaprogramstoredinafile

calledecho.c,thecompileropenstheecho.cfileandreadsits

contents.Whenthecompilerfinishes,itclosesthefile.Other

programs,suchaswordprocessors,notonlyopen,read,and

closefiles,theyalsowritetothem.

C,beingpowerful,flexible,andsoon,hasmanylibrary

functionsforopening,reading,writing,andclosingfiles.Onone

level,itcandealwithfilesbyusingthebasicfiletoolsofthe

hostoperatingsystem.Thisiscalledlow-levelI/O.Becauseof

themanydifferencesamongcomputersystems,itisimpossible

tocreateastandardlibraryofuniversallow-levelI/Ofunctions,

andANSICdoesnotattempttodoso;however,Calsodeals

withfilesonasecondlevelcalledthestandardI/Opackage.



Thisinvolvescreatingastandardmodelandastandardsetof

I/Ofunctionsfordealingwithfiles.Atthishigherlevel,

differencesbetweensystemsarehandledbyspecificC

implementationssothatyoudealwithauniforminterface.

Whatsortofdifferencesarewetalkingabout?Different

systems,forexample,storefilesdifferently.Somestorethefile

contentsinoneplaceandinformationaboutthefileelsewhere.

Somebuildadescriptionofthefileintothefileitself.Indealing

withtext,somesystemsuseasinglenewlinecharactertomark

theendofaline.Othersmightusethecombinationofthe

carriagereturnandlinefeedcharacterstorepresenttheendof

aline.Somesystemsmeasurefilesizestothenearestbyte;

somemeasureinblocksofbytes.

WhenyouusethestandardI/Opackage,youareshieldedfrom

thesedifferences.Therefore,tocheckforanewline,youcan

useif(ch=='\n').Ifthesystemactuallyusesthecarriagereturn/linefeedcombination,theI/Ofunctionsautomatically

translatebackandforthbetweenthetworepresentations.

Conceptually,theCprogramdealswithastreaminsteadof

directlywithafile.Astreamisanidealizedflowofdatato

whichtheactualinputoroutputismapped.Thatmeansvarious

kindsofinputwithdifferingpropertiesarerepresentedby

streamswithmoreuniformproperties.Theprocessofopeninga

filethenbecomesoneofassociatingastreamwiththefile,and

readingandwritingtakeplaceviathestream.

Chapter13discussesfilesingreaterdetail.Forthischapter,

simplynotethatCtreatsinputandoutputdevicesthesameas

ittreatsregularfilesonstoragedevices.Inparticular,the

keyboardandthedisplaydevicearetreatedasfilesopened

automaticallybyeveryCprogram.Keyboardinputis

representedbyastreamcalledstdin,andoutputtothescreen

(orteletypeorotheroutputdevice)isrepresentedbyastream

calledstdout.Thegetchar(),putchar(),printf(),and

scanf()functionsareallmembersofthestandardI/O



package,andtheydealwiththesetwostreams.

Oneimplicationofallthisisthatyoucanusethesame

techniqueswithkeyboardinputasyoudowithfiles.For

example,aprogramreadingafileneedsawaytodetectthe

endofthefilesothatitknowswheretostopreading.

Therefore,Cinputfunctionscomeequippedwithabuilt-in,endof-filedetector.Becausekeyboardinputistreatedlikeafile,

youshouldbeabletousethatend-of-filedetectortoterminate

keyboardinput,too.Let'sseehowthisisdone,beginningwith

files.



TheEndofFile

Acomputeroperatingsystemneedssomewaytotellwhere

eachfilebeginsandends.Onemethodtodetecttheendofa

fileistoplaceaspecialcharacterinthefiletomarktheend.

Thisisthemethodonceused,forexample,inCP/M,IBM-DOS,

andMS-DOStextfiles.Today,theseoperatingsystemsmayuse

anembeddedCtrl+Zcharactertomarktheendsoffiles.Atone

time,thiswasthesolemeanstheseoperatingsystemsused,

butthereareotheroptionsnow,suchaskeepingtrackofthe

filesize.Soamoderntextfilemayormaynothavean

embeddedCtrl+Z,butifitdoes,theoperatingsystemwilltreat

itasanend-of-filemarker.Figure8.2illustratesthisapproach.



Figure8.2.Afilewithanend-of-filemarker.



Asecondapproachisfortheoperatingsystemtostore

informationonthesizeofthefile.Ifafilehas3000bytesanda

programhasread3000bytes,theprogramhasreachedthe

end.MS-DOSanditsrelativesusethisapproachforbinaryfiles

becausethismethodallowsthefilestoholdallcharacters,

includingCtrl+Z.NewerversionsofDOSalsousethisapproach

fortextfiles.Unixusesthisapproachforallfiles.

Chandlesthisvarietyofmethodsbyhavingthegetchar()

functionreturnaspecialvaluewhentheendofafileisreached,

regardlessofhowtheoperatingsystemactuallydetectstheend

offile.ThenamegiventothisvalueisEOF(endoffile).

Therefore,thereturnvalueforgetchar()whenitdetectsan

endoffileisEOF.Thescanf()functionalsoreturnsEOFon

detectingtheendofafile.Typically,EOFisdefinedinthe

stdio.hfileasfollows:



#defineEOF(-1)



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 8. Character Input/Output and Input Validation

Tải bản đầy đủ ngay(0 tr)

×