Tải bản đầy đủ - 0 (trang)
Chapter 17. INPUT, OUTPUT, AND FILES

Chapter 17. INPUT, OUTPUT, AND FILES

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

Incoreformatting

DiscussingC++inputandoutput(I/O,forshort)posesa

problem.Ontheonehand,practicallyeveryprogramusesinput

andoutput,andlearninghowtousethemisoneofthefirst

tasksfacingsomeonelearningacomputerlanguage.Onthe

otherhand,C++usesmanyofitsmoreadvancedlanguage

featurestoimplementinputandoutput,includingclasses,

derivedclasses,functionoverloading,virtualfunctions,

templates,andmultipleinheritance.Thus,toreallyunderstand

C++I/O,youmustknowalotofC++.Togetyoustarted,the

earlychaptersoutlinedthebasicwaysforusingtheistream

classobjectcinandtheostreamclassobjectcoutforinput

andoutput.Nowwe'lltakealongerlookatC++'sinputand

outputclasses,seeinghowtheyaredesignedandlearninghow

tocontroltheoutputformat.(Ifyou'veskippedafewchapters

justtolearnadvancedformatting,youcanskimthesectionson

thattopic,notingthetechniquesandignoringthe

explanations.)

TheC++facilitiesforfileinputandoutputarebasedonthe

samebasicclassdefinitionsthatcinandcoutarebasedon,so

thischapterusesthediscussionofconsoleI/O(keyboardand

screen)asaspringboardtoinvestigatingfileI/O.

TheANSI/ISOC++standardscommitteehasworkedtomake

C++I/OmorecompatiblewithexistingCI/O,andthishas

producedsomechangesfromtraditionalC++practices.



AnOverviewofC++InputandOutput

Mostcomputerlanguagesbuildinputandoutputintothe

languageitself.Forexample,ifyoulookthroughthelistsof

keywordsforlanguageslikeBASICorPascal,you'llseethat

PRINTstatements,writelnstatements,andthelike,arepart

ofthelanguagevocabulary.ButneitherCnorC++havebuilt

inputandoutputintothelanguage.Ifyoulookthroughthe

keywordsfortheselanguages,youfindforandif,butnothing

relatingtoI/O.CoriginallyleftI/Otocompilerimplementers.

Onereasonforthiswastogiveimplementersthefreedomto

designI/Ofunctionsthatbestfitthehardwarerequirementsof

thetargetcomputer.Inpractice,mostimplementersbasedI/O

onasetoflibraryfunctionsoriginallydevelopedfortheUNIX

environment.ANSICformalizedrecognitionofthisI/O

package,calledtheStandardInput/Outputpackage,bymaking

itamandatorycomponentofthestandardClibrary.C++also

recognizesthispackage,soifyou'refamiliarwiththefamilyof

Cfunctionsdeclaredinthestdio.hfile,youcanusethemin

C++programs.(Newerimplementationsusethecstdioheader

filetosupportthesefunctions.)

C++,however,reliesuponaC++solutionratherthanaC

solutiontoI/O,andthatsolutionisasetofclassesdefinedin

theiostream(formerlyiostream.h)andfstream(formerly

fstream.h)headerfiles.Thisclasslibraryisnotpartofthe

formallanguagedefinition(cinandistreamarenot

keywords);afterall,acomputerlanguagedefinesrulesforhow

todothings,suchascreateclasses,anddoesn'tdefinewhat

youshouldcreatefollowingthoserules.But,justasC

implementationscomewithastandardlibraryoffunctions,C++

comeswithastandardlibraryofclasses.Atfirst,thatstandard

classlibrarywasaninformalstandardconsistingsolelyofthe

classesdefinedintheiostreamandfstreamheaderfiles.The

ANSI/ISOC++committeedecidedtoformalizethislibraryasa



standardclasslibraryandtoaddafewmorestandardclasses,

suchasthosediscussedinChapter16,"ThestringClassand

theStandardTemplateLibrary."Thischapterdiscusses

standardC++I/O.Butfirst,let'sexaminetheconceptual

frameworkforC++I/O.



StreamsandBuffers

AC++programviewsinputoroutputasastreamofbytes.On

input,aprogramextractsbytesfromaninputstream,andon

output,aprograminsertsbytesintotheoutputstream.Fora

text-orientedprogram,eachbytecanrepresentacharacter.

Moregenerally,thebytescanformabinaryrepresentationof

characterornumericdata.Thebytesinaninputstreamcan

comefromthekeyboard,buttheyalsocancomefroma

storagedevice,suchasaharddisk,orfromanotherprogram.

Similarly,thebytesinanoutputstreamcanflowtothescreen,

toaprinter,toastoragedevice,ortoanotherprogram.A

streamactsasanintermediarybetweentheprogramandthe

stream'ssourceordestination.ThisapproachenablesaC++

programtotreatinputfromakeyboardinthesamemannerit

treatsinputfromafile;theC++programmerelyexaminesthe

streamofbyteswithoutneedingtoknowfromwherethebytes

come.Similarly,byusingstreams,aC++programcanprocess

outputinamannerindependentofwherethebytesaregoing.

Managinginput,then,involvestwostages:

Associatingastreamwithaninputtoaprogram

Connectingthestreamtoafile

Inotherwords,aninputstreamneedstwoconnections,oneat

eachend.Thefile-endconnectionprovidesasourceforthe

stream,andtheprogram-endconnectiondumpsthestream

outflowintotheprogram.(Thefile-endconnectioncanbeafile,



butitalsocanbeadevice,suchasakeyboard.)Similarly,

managingoutputinvolvesconnectinganoutputstreamtothe

programandassociatingsomeoutputdestinationwiththe

stream.It'slikeplumbingwithbytesinsteadofwater(see

Figure17.1).



Figure17.1.C++inputandoutput.



Usually,inputandoutputcanbehandledmoreefficientlyby

usingabuffer.Abufferisablockofmemoryusedasan

intermediate,temporarystoragefacilityforthetransferof

informationfromadevicetoaprogramorfromaprogramtoa

device.Typically,deviceslikediskdrivestransferinformationin

blocksof512bytesormore,whileprogramsoftenprocess

informationonebyteatatime.Thebufferhelpsmatchthese

twodisparateratesofinformationtransfer.Forexample,

assumeaprogramissupposedtocountthenumberofdollar



signsinahard-diskfile.Theprogramcouldreadonecharacter

fromthefile,processit,readthenextcharacterfromthefile,

andsoon.Readingafileacharacteratatimefromadisk

requiresalotofhardwareactivityandisslow.Thebuffered

approachistoreadalargechunkfromthedisk,storethe

chunkinthebuffer,andreadthebufferonecharacteratatime.

Becauseitismuchquickertoreadindividualbytesofdatafrom

memorythanfromaharddisk,thisapproachismuchfasteras

wellaseasieronthehardware.Ofcourse,aftertheprogram

reachestheendofthebuffer,theprogramthenshouldread

anotherchunkofdatafromthedisk.Theprincipleissimilarto

thatofawaterreservoirthatcollectsmegagallonsofrunoff

waterduringabigstorm,thenfeedswatertoyourhomeata

morecivilizedrateofflow(seeFigure17.2).Similarly,on

outputaprogramcanfirstfillthebuffer,thentransfertheentire

blockofdatatoaharddisk,clearingthebufferforthenext

batchofoutput.Thisiscalledflushingthebuffer.Perhapsyou

cancomeupwithyourownplumbing-basedanalogyforthat

process.



Figure17.2.Astreamwithabuffer.



Keyboardinputprovidesonecharacteratatime,sointhatcase

aprogramdoesn'tneedabuffertohelpmatchdifferentdata

transferrates.However,bufferedkeyboardinputallowsthe

usertobackupandcorrectinputbeforetransmittingittoa

program.AC++programnormallyflushestheinputbuffer

whenyoupress.That'swhytheexamplesinthisbook

don'tbeginprocessinginputuntilyoupress.Foroutput

tothescreen,aC++programnormallyflushestheoutput

bufferwhenyoutransmitanewlinecharacter.Dependingupon

theimplementation,aprogrammayflushinputonother

occasions,too,suchasimpendinginput.Thatis,whena

programreachesaninputstatement,itflushesanyoutput

currentlyintheoutputbuffer.C++implementationsthatare



consistentwithANSICshouldbehaveinthatmanner.



Streams,Buffers,andtheiostreamFile

Thebusinessofmanagingstreamsandbufferscangetabit

complicated,butincludingtheiostream(formerlyiostream.h)

filebringsinseveralclassesdesignedtoimplementandmanage

streamsandbuffersforyou.ThenewestversionofC++I/O

actuallydefinesclasstemplatesinordertosupportbothchar

andwchar_tdata.Byusingthetypedeffacility,C++makes

thecharspecializationsofthesetemplatesmimicthetraditional

non-templateI/Oimplementation.Herearesomeofthose

classes(seeFigure17.3):

Thestreambufclassprovidesmemoryforabufferalong

withclassmethodsforfillingthebuffer,accessingbuffer

contents,flushingthebuffer,andmanagingthebuffer

memory.

Theios_baseclassrepresentsgeneralpropertiesofa

stream,suchaswhetherit'sopenforreadingandwhether

it'sabinaryoratextstream.

Theiosclassisbasedonios_base,anditincludesa

pointermembertoastreambufobject.

Theostreamclassderivesfromtheiosclassandprovides

outputmethods.

Theistreamclassalsoderivesfromtheiosclassand

providesinputmethods.

Theiostreamclassisbasedontheistreamandostream

classesandthusinheritsbothinputandoutputmethods.



Figure17.3.SomeI/Oclasses.



Tousethesefacilities,youuseobjectsoftheappropriate

classes.Forexample,useanostreamobjectsuchascoutto

handleoutput.Creatingsuchanobjectopensastream,

automaticallycreatesabuffer,andassociatesitwiththe

stream.Italsomakestheclassmemberfunctionsavailableto

you.



RedefiningI/O

TheISO/ANSIC++standardhasrevisedI/Oacoupleofways.First,

there'sthechangefromostream.htoostream,withostreamplacing

theclassesinthestdnamespace.Second,theI/Oclasseshavebeen

rewritten.Tobeaninternationallanguage,C++hadtobeableto

handleinternationalcharactersetsthatrequirea16-bitorwider

charactertype.Sothelanguageaddedthewchar_t(or"wide")

charactertypetothetraditional8-bitchar(or"narrow")type.Eachtype



needsitsownI/Ofacilities.Ratherthandeveloptwoseparatesetsof

classes,thestandardscommitteedevelopedatemplatesetofI/O

classes,includingbasic_istream>and

basic_ostream>.Thetraits

template,inturn,isatemplateclassdefiningparticulartraitsfora

charactertype,suchashowtocompareforequalityanditsEOFvalue.

Thestandardprovidescharandwchar_tspecializationsoftheI/O

classes.Forexample,istreamandostreamaretypedefsforchar

specializations.Similarly,wistreamandwostreamarewchar_t

specializations.Forexample,thereisawcoutobjectforoutputtingwide

characterstreams.Theostreamheaderfilecontainsthesedefinitions.

Certaintype-independentinformationthatusedtobekeptintheios

baseclasshasbeenmovedtothenewios_baseclass.Thisincludesthe

variousformattingconstantssuchasios::fixed,whichnowis

ios_base::fixed.Also,ios_basecontainssomeoptionsthatweren't

availableintheoldios.

Insomecases,thechangeinthefilenamecorrespondswiththechange

inclassdefinitions.InMicrosoftVisualC++6.0,forexample,youcan

includeiostream.handgettheoldclassdefinitionsorincludeiostream

andgetthenewclassdefinitions.However,dualversionslikethisare

notthegeneralrule.



TheC++iostreamclasslibrarytakescareofmanydetailsfor

you.Forexample,includingtheiostreamfileinaprogram

createseightstreamobjects(fourfornarrowcharactersstream

andfourforwidecharacterstreams)automatically:

Thecinobjectcorrespondstothestandardinputstream.

Bydefault,thisstreamisassociatedwiththestandardinput

device,typicallyakeyboard.Thewcinobjectissimilar,but

workswiththewchar_ttype.

Thecoutobjectcorrespondstothestandardoutputstream.

Bydefault,thisstreamisassociatedwiththestandard

outputdevice,typicallyamonitor.Thewcoutobjectis

similar,butworkswiththewchar_ttype.



Thecerrobjectcorrespondstothestandarderrorstream,

whichyoucanusefordisplayingerrormessages.By

default,thisstreamisassociatedwiththestandardoutput

device,typicallyamonitor,andthestreamisunbuffered.

Thismeansthatinformationissentdirectlytothescreen

withoutwaitingforabuffertofillorforanewlinecharacter.

Thewcerrobjectissimilar,butworkswiththewchar_t

type.

Theclogobjectalsocorrespondstothestandarderror

stream.Bydefault,thisstreamisassociatedwiththe

standardoutputdevice,typicallyamonitor,andthestream

isbuffered.Thewclogobjectissimilar,butworkswiththe

wchar_ttype.

Whatdoesitmeantosayanobjectrepresentsastream?Well,

forexample,whentheiostreamfiledeclaresacoutobjectfor

yourprogram,thatobjectwillhavedatamembersholding

informationrelatingtooutput,suchasthefieldwidthstobe

usedindisplayingdata,thenumberofplacesafterthedecimal

touse,whatnumberbasetousefordisplayingintegers,and

theaddressofastreambufobjectdescribingthebufferusedto

handletheoutputflow.Astatementsuchas

cout<<"Bjarnefree";

placesthecharactersfromthestring"Bjarnefree"intothe

buffermanagedbycoutviathepointed-tostreambufobject.

Theostreamclassdefinestheoperator<<()functionusedin

thisstatement,andtheostreamclassalsosupportsthecout

datamemberswithavarietyofotherclassmethods,suchas

theonesthischapterdiscusseslater.Furthermore,C++seesto

itthattheoutputfromthebufferisdirectedtothestandard

output,usuallyamonitor,providedbytheoperatingsystem.In



short,oneendofastreamisconnectedtoyourprogram,the

otherendisconnectedtothestandardoutput,andthecout

object,withthehelpofatypestreambufobject,managesthe

flowofbytesthroughthestream.



Redirection

Thestandardinputandoutputstreamsnormallyconnecttothe

keyboardandthescreen.Butmanyoperatingsystems,

includingUnix,Linux,andMS-DOS,supportredirection,a

facilitythatletsyouchangetheassociationsforthestandard

inputandthestandardoutput.Suppose,forexample,youhave

anexecutableDOSC++programcalledcounter.exethat

countsthenumberofcharactersinitsinputandreportsthe

result.(FromvariousversionsofWindowsyoucangotoStart,

clickPrograms,thenclicktheMS-DOSCommandPrompticon

orCommandPrompticontostartanMD-DOSwindow.)A

samplerunmightlooklikethis:

C>counter

Hello

andgoodbye!

Control-Z¬simulatedend-of-file

Inputcontained19characters.

C>

Here,inputcamefromthekeyboard,andoutputwenttothe

screen.



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

Chapter 17. INPUT, OUTPUT, AND FILES

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

×