Tải bản đầy đủ - 0 (trang)
Chapter 13. Input/Output Using Stream Classes

Chapter 13. Input/Output Using Stream Classes

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

Chapter13.Input/OutputUsingStream

Classes

13.1CommonBackgroundofI/OStreams

13.2FundamentalStreamClassesandObjects

13.3StandardStreamOperators<>

13.4StateofStreams

13.5StandardInput/OutputFunctions

13.6Manipulators

13.7Formatting

13.8Internationalization

13.9FileAccess

13.10ConnectingInputandOutputStreams

13.11StreamClassesforStrings

13.12Input/OutputOperatorsforUser-DefinedTypes

13.13TheStreamBufferClasses

13.14PerformanceIssues

TheclassesforI/OformanimportantpartoftheC++standardlibrary;a

programwithoutI/Oisnotofmuchuse.Actually,theI/Oclassesfromthe

C++standardlibraryarenotrestrictedtofilesortoscreenandkeyboard.

Instead,theyformanextensibleframeworkfortheformattingofarbitrary

dataandaccesstoarbitrary"externalrepresentations."

TheIOStreamlibrary,astheclassesforI/Oarecalled,istheonlypartof

theC++standardlibrarythatwasusedwidelypriortothestandardization

ofC++.EarlydistributionsofC++systemscamewithasetofclasses

developedatAT&TthatestablishedadefactostandardfordoingI/O.

Althoughtheseclasseshaveundergoneseveralchangestofit

consistentlyintotheC++standardlibraryandtosuitnewneeds,the

basicprinciplesoftheIOStreamlibraryremainunchanged.

Thischapterfirstpresentsageneraloverviewofthemostimportant

componentsandtechniques,andthendemonstratesindetailhowthe

IOStreamlibrarycanbeusedinpractice.Itsuserangesfromsimple

formattingtotheintegrationofnewexternalrepresentations(atopicthat



isoftenaddressedimproperly).

ThischapterdoesnotattempttodiscussallaspectsoftheIOStream

libraryindetail;todothatwouldtakeanentirebookbyitself.Fordetails

notfoundhere,pleaseconsultoneofthebooksthatfocusontheI/O

streamlibraryorthereferencemanualoftheC++standardlibrary.

ManythankstoDietmarKühl,whoisanexpertonI/Oand

internationalizationintheC++standardlibraryandgaveverymuch

feedbackandwrotesomepartsofthischapter.

RecentChangesintheIOStreamLibrary

Forthosealreadyfamiliarwiththe"old-fashioned"IOStreamlibrary,this

sectionoutlineschangesintroducedduringthestandardizationprocess.

AlthoughthebasicsoftheI/Ostreamclassesremainedunchanged,

someimportantfeaturesallowingadditionalcustomizationwere

introduced.Hereisabrieflistofthemajorchanges:

I/Obecameinternationalized.

Thestringstreamclassesforcharacterarraysoftypechar*were

replacedwithclassesthatusethestringtypesoftheC++

standardlibrary.Theformerclassesarestillretainedforbackward

compatibility,buttheiruseisdeprecated.[1]

Exceptionhandlingwasintegratedintostateanderrorhandling.

TheIOStreamlibraryclassessupportingassignment(thoseending

in_withassign)werereplacedwithadifferentapproach

availabletoallstreamclasses.

TheclassesfromtheIOStreamlibraryweremadetemplatesto

supportdifferentcharacterrepresentations.Asasideeffect,this

renderssimpleforwarddeclarationsofstreamclassesillegal.A

headerwasintroducedtoprovidetheappropriatedeclarations.So,

insteadofusing



classostream;//wrong



thisnewheadershouldbeused:



#include//OK

LiketheotherpartsoftheC++standardlibrary,allsymbolsofthe

IOStreamlibraryarenowdeclaredinthenamespacestd.



13.1CommonBackgroundofI/OStreams

Beforegoingintodetailsaboutstreamclasses,Ibrieflydiscussthe

generallyknownaspectsofstreamstoprovideacommonbackground.

Thissectioncouldbeskippedbyreadersfamiliarwithiostreambasics.



13.1.1StreamObjects

InC++,I/Oisperformedbyusingstreams.Astreamisa"streamofdata"

inwhichcharactersequences"flow."Followingtheprinciplesofobject

orientation,astreamisanobjectwithpropertiesthataredefinedbya

class.Outputisinterpretedasdataflowingintoastream;inputis

interpretedasdataflowingoutofastream.Globalobjectsarepredefined

forthestandardI/Ochannels.



13.1.2StreamClasses

JustastherearedifferentkindsofI/O(forexample,input,output,andfile

access),therearedifferentclassesdependingonthetypeofI/O.The

followingarethemostimportantstreamclasses:

Classistream

Definesinputstreamsthatcanbeusedtoreaddata.

Classostream

Definesoutputstreamsthatcanbeusedtowritedata.



Bothclassesareinstantiationsoftemplateclasses,namelyoftheclasses

basic_istream<>andbasic_ostream<>usingcharasthe

charactertype.Actually,thewholeIOStreamlibrarydoesnotdependon

aspecificcharactertype.Insteadthecharactertypeusedisatemplate

argumentformostoftheclassesintheIOStreamlibrary.This

parameterizationcorrespondstothestringclassesandisusedfor

internationalization(seealsoSection14).

Thissectionconcentratesonoutputtoandoutputfrom"narrowstreams";

thatis,streamsdealingwithcharasthecharactertype.Laterinthis

chapterthediscussionisextendedtostreamsthathaveothercharacter

types.



13.1.3GlobalStreamObjects

TheIOStreamlibrarydefinesseveralglobalobjectsoftypeistream

andostream.TheseobjectscorrespondtothestandardI/Ochannels:

cin



cin(ofclassistream)isthestandardinputchannelthatisused

foruserinput.ThisstreamcorrespondstoC'sstdin.Normally,

thisstreamisconnectedtothekeyboardbytheoperatingsystem.

cout



cout(ofclassostream)isthestandardoutputchannelthatis

usedforprogramoutput.ThisstreamcorrespondstoC'sstdout.

Normally,thisstreamisconnectedtothemonitorbytheoperating

system.

cerr



cerr(ofclassostream)isthestandarderrorchannelthatis

usedforallkindsoferrormessages.ThisstreamcorrespondstoC's

stderr.Normally,thisstreamisalsoconnectedtothemonitorby

theoperatingsystem.Bydefault,cerrisnotbuffered.



clog



clog(ofclassostream)isthestandardloggingchannel.Thereis

noCequivalentforthisstream.Bydefault,thisstreamisconnected

tothesamedestinationascerr,withthedifferencethatoutputto

clogisbuffered.

Theseparationof"normal"outputanderrormessagesmakesitpossible

totreatthesetwokindsofoutputdifferentlywhenexecutingaprogram.

Forexample,thenormaloutputofaprogramcanberedirectedintoafile

whiletheerrormessagesarestillappearingontheconsole.Ofcourse,

thisrequiresthattheoperatingsystemsupportsredirectionofthe

standardI/Ochannels(mostoperatingsystemsdo).Thisseparationof

standardchannelsoriginatesfromtheUNIXconceptofI/Oredirection.



13.1.4StreamOperators

Theshiftoperators<>foroutputareoverloadedforthe

correspondingstreamclasses.Forthisreason,inC++the"shift

operators"becamethe"I/Ooperators."[2]Usingtheseoperators,itis

possibletochainmultipleI/Ooperations.

Forexample,foreachiteration,thefollowingloopreadstwointegers

fromthestandardinput(aslongasonlyintegersareentered)andwrites

themtothestandardoutput:



inta,b;



//aslongasinputofaandbissuccessful

while(std::cin>>a>>b){

//outputaandb

std::cout<<"a:"<
}

13.1.5Manipulators



Attheendofmostoutputstatements,aso-calledmanipulatoriswritten:



std::cout<
Manipulatorsarespecialobjectsthatareusedto,guesswhat,

manipulateastream.Often,manipulatorsonlychangethewayinputis

interpretedoroutputisformatted,likethemanipulatorsforthenumeric

basesdec,hex,andoct.Thus,manipulatorsforostreamsdo

notnecessarilycreateoutput,andmanipulatorsforistreamsdonot

necessaryconsumeinput.Buttherearealsomanipulatorsthatactually

triggersomeimmediateaction.Forexample,amanipulatorcanbeused

toflushtheoutputbufferortoskipwhitespaceintheinputbuffer.

Themanipulatorendlmeans"endline"anddoestwothings:

1. Outputsanewline(thatis,thecharacter'\n')

Flushestheoutputbuffer(forcesawriteofallbuffereddataforthe

givenstreamusingthestreammethodflush())

ThemostimportantmanipulatorsdefinedbytheIOStreamlibraryare

providedinTable13.1.

Section13.6,discussesmanipulatorsinmoredetail,includingthosethat

aredefinedintheIOStreamlibrary,anddescribeshowtodefineyour

ownmanipulators.

Table13.1.TheIOStreamLibrary'sMostImportantManipulators

Manipulator Class

Meaning

endl

ostream Outputs'\n'andflushestheoutput

buffer



ends

flush

ws



ostream Outputs'\0'

ostream Flushestheoutputbuffer

istream Readsanddiscardswhitespaces



13.1.6ASimpleExample



Theuseofthestreamclassesisdemonstratedbythefollowingexample.

Thisprogramreadstwofloating-pointvaluesandoutputstheirproduct:



//io/io1.cpp

#include

#include

usingnamespacestd;

intmain()

{

doublex,y;//operands



//printheaderstring

cout<<"Multiplicationoftwofloatingpointva



//readfirstoperand

cout<<"firstoperand:";

if(!(cin>>x)){

/*inputerror

*=>errormessageandexitprogramwithe

*/

cerr<<"errorwhilereadingthefirstfloat

<
returnEXIT_FAILURE;

}



//readsecondoperand

cout<<"secondoperand:";

if(!(cin>>y)){

/*inputerror

*=>errormessageandexitprogramwitherror



*/

cerr<<"errorwhilereadingthesecondfloatin

<
returnEXIT_FAILURE;

}



//printoperandsandresult

cout<
}



13.2FundamentalStreamClassesandObjects

13.2.1ClassesandClassHierarchy

ThestreamclassesoftheIOStreamlibraryformahierarchy,asshownin

Figure13.1.Fortemplateclasses,theupperrowshowsthenameofthe

templateclass,andthelowerrowpresentsthenamesofthe

instantiationsforthecharactertypescharandwchar_t.

Figure13.1.ClassHierarchyoftheFundamentalStreamClasses



Theclassesinthisclasshierarchyplaythefollowingroles:

Thebaseclassios_basedefinesthepropertiesofallstream

classesindependentofthecharactertypeandthecorresponding

charactertraits.Mostofthisclassconsistsofcomponentsand

functionsforstateandformatflags.

Theclasstemplatebasic_ios<>isderivedfromios_base

anditdefinesthecommonpropertiesofallstreamclassesthat

dependonthecharactertypesandthecorrespondingcharacter

traits.Thesepropertiesincludethedefinitionofthebufferusedby

thestream.Thebufferisanobjectofaclassderivedfromthe

templateclassbasic_streambuf<>withthecorresponding

templateinstantiation.Itperformstheactualreadingand/orwriting.

Theclasstemplatesbasic_istream<>and

basic_ostream<>derivevirtuallyfrombasic_ios<>,and

defineobjectsthatcanbeusedforreadingorwritingrespectively.

Likebasic_ios<>,theseclassesaretemplatesthatare

parameterizedwithacharactertypeanditstraits.When

internationalizationdoesnotmatter,thecorrespondinginstantiations

forthecharactertypechar(namely,istreamandostream)

areused.

Theclasstemplatebasic_iostream<>derivesfromboth

basic_istream<>andbasic_ostream<>.Thisclass

templatedefinesobjectsthatcanbeusedforbothreadingand

writing.

Theclasstemplatebasic_streambuf<>istheheartofthe

IOStreamlibrary.Thisclassdefinestheinterfacetoall

representationsthatcanbewrittentoorreadfrombystreams.Itis

usedbytheotherstreamclassestoperformtheactualreadingand

writingofcharacters.Foraccesstosomeexternalrepresentation,

classesarederivedfrombasic_strearabuf<>.Seethe

followingsubsectionfordetails.



PurposeoftheStreamBufferClasses

TheIOStreamlibraryisdesignedwitharigidseparationof

responsibilities.Theclassesderivedfrombasic_ios"only"handle

formattingofthedata.[3]Theactualreadingandwritingofcharactersis

performedbythestreambuffersmaintainedbythebasic_ios

subobjects.Thestreambufferssupplycharacterbuffersforreadingand

writing.Inaddition,anabstractionfromtheexternalrepresentation(for

examplefilesorstrings)isformedbythestreambuffers.

Thus,streambuffersplayanimportantrolewhenperformingI/Owith

newexternalrepresentations(suchassocketsorgraphicaluserinterface

components),redirectingstreams,orcombiningstreamstoform

pipelines(forexample,tocompressoutputbeforewritingtoanother

stream).Also,thestreambuffersynchronizestheI/Owhendoing

simultaneousI/Oonthesameexternalrepresentation.Thedetailsabout

thesetechniquesareexplainedinSection13.10.2.

Byusingstreambuffersitisquiteeasytodefineaccesstoanew

"externalrepresentation"likeanewstoragedevice.Allthathastobe

doneistoderiveanewstreambufferclassfrom

basic_streambuf<>(oranappropriatespecialization)anddefine

functionsforreadingand/orwritingcharactersforthisnewexternal

representation.AlloptionsforformattedI/Oareavailableautomaticallyif

astreamobjectisinitializedtouseanobjectofthenewstreambuffer

class.Section13.13,explainshowtodefinenewstreambuffersfor

accesstospecialstoragedevices.

DetailedClassDefinitions

LikealltemplateclassesintheIOStreamlibrary,thetemplateclass

basic_ios<>isparameterizedwithtwoargumentsanddefinedas



namespacestd{

template
classtraits=char_traits>



classbasic_ios;

}

Thetemplateargumentsarethecharactertypeusedbythestream

classesandaclassdescribingthetraitsofthecharactertypethatare

usedbythestreamclasses.

Examplesoftraitsdefinedinthetraitsclassarethevalueusedto

representend-of-file[4]andtheinstructionsforhowtocopyormovea

sequenceofcharacters.Normally,thetraitsforacharactertypeare

coupledwiththecharactertype,therebymakingitreasonabletodefinea

templateclassthatisspecializedforspecificcharactertypes.Hence,the

traitsclassdefaultstochar_traitsifcharTisthe

charactertypeargument.TheC++standardlibraryprovides

specializationsoftheclasschar_traitsforthecharactertypes

charandwchar_t.Formoredetailsaboutcharactertraits,see

Section14.1.2.

Therearetwoinstantiationsoftheclassbasic_ios<>forthetwo

charactertypesusedmostoften:



namespacestd{

typedefbasic_iosios;

typedefbasic_ioswios;

}

Thetypeioscorrespondstothebaseclassofthe"old-fashioned"

IOStreamlibraryfromAT&Tandcanbeusedforcompatibilityinolder

C++programs.

Thestreambufferclassusedbybasic_iosisdefinedsimilarly:



namespacestd{

template
classtraits=char_traits>

classbasic_streambuf;



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

Chapter 13. Input/Output Using Stream Classes

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

×