Introductiontothef77I/OLibrary DavidL.Wasley UniversityofCalifornia,Berkeley Berkeley,California94720 ABSTRACT Thef77I/OLibraryimplementsANSI1978FORTRANstandardinputandoutput withafewminorexceptions.Wherethestandardisvague,wehavetriedtoprovideflexibilitywithintheconstraintsoftheUNIX◯roperatingsystem.TheI/O LibrarywaswrittenoriginallybyPeterJ.WeinbergeratBellLabs.Anumberof logicalextensionsandenhancementshavebeenprovidedbythisauthor. April1983 Introductiontothef77I/OLibrary DavidL.Wasley UniversityofCalifornia,Berkeley Berkeley,California94720 Thef77I/Olibrary,libI77.a,includesroutinestoperformallofthestandardtypesofFOR-TRANinputandoutput.SeveralenhancementsandextensionstoFORTRANI/Ohavebeen added.Thef77libraryroutinesusetheCstdiolibraryroutinestoprovideefficientbufferingfor fileI/O. 1.FORTRANI/O TherequirementsoftheANSIstandardimposesignificantoverheadonprogramsthatdo largeamountsofI/O.FormattedI/Ocanbevery‘‘expensive’’whiledirectaccessbinaryI/Ois usuallyveryefficient.BecauseofthecomplexityofFORTRANI/O,somegeneralconceptsdeserve clarification. 1.1.TypesofI/O TherearethreeformsofI/O:formatted,unformatted,andlist-directed.Thelastis relatedtoformattedbutdoesnotobeyalltherulesforformattedI/O.Therearetwomodesof accesstoexternalandinternalfiles:directandsequential.Thedefinitionofalogicalrecord dependsuponthecombinationofI/OformandmodespecifiedbytheFORTRANI/Ostatement. 1.1.1.Directaccess Alogicalrecordinadirectaccessexternalfileisastringofbytesofalengthspecified whenthefileisopened.Readandwritestatementsmustnotspecifylogicalrecordslongerthan theoriginalrecordsizedefinition.Shorterlogicalrecordsareallowed.Unformatteddirectwrites leavetheunfilledpartoftherecordundefined.Formatteddirectwritescausetheunfilledrecord tobepaddedwithblanks. 1.1.2.Sequentialaccess Logicalrecordsinsequentiallyaccessedexternalfilesmaybeofarbitraryandvariable length.Logicalrecordlengthforunformattedsequentialfilesisdeterminedbythesizeofitems intheiolist.TherequirementsofthisformofI/Ocausetheexternalphysicalrecordsizetobe somewhatlargerthanthelogicalrecordsize.Forformattedwritestatements,logicalrecord lengthisdeterminedbytheformatstatementinteractingwiththeiolistatexecutiontime.The ‘‘newline’’characteristhelogicalrecorddelimiter.Formattedsequentialaccesscausesoneor morelogicalrecordsendingwith‘‘newline’’characterstobereadorwritten. 1.1.3.ListdirectedI/O Logicalrecordlengthforlist-directedI/Oisrelativelymeaningless.Onoutput,therecord lengthisdependentonthemagnitudeofthedataitems.Oninput,therecordlengthisdeterminedbythedatatypesandthefilecontents. 1.1.4.InternalI/O Thelogicalrecordlengthforaninternalreadorwriteisthelengthofthecharactervariableorarrayelement.Thusasimplecharactervariableisasinglelogicalrecord.Acharactervariablearrayissimilartoafixedlengthdirectaccessfile,andobeysthesamerules.Unformatted -2-I/Oisnotallowedon"internal"files. 1.2.I/Oexecution NotethateachexecutionofaFORTRANunformattedI/Ostatementcausesasinglelogical recordtobereadorwritten.EachexecutionofaFORTRANformattedI/Ostatementcausesone ormorelogicalrecordstobereadorwritten. Aslash,‘‘/’’,willterminateassignmentofvaluestotheinputlistduringlist-directedinput andtheremainderofthecurrentinputlineisskipped.Thestandardisrathervagueonthispoint butseemstorequirethatanewexternallogicalrecordbefoundatthestartofanyformatted input.Thereforedatafollowingtheslashisignoredandmaybeusedtocommentthedatafile. Directaccesslist-directedI/Oisnotallowed.UnformattedinternalI/Oisnot allowed.Boththeabovewillbecaughtbythecompiler.AllotherflavorsofI/Oareallowed, althoughsomearenotpartoftheANSIstandard. AnyerrordetectedduringI/Oprocessingwillcausetheprogramtoabortunlessalternative actionhasbeenprovidedspecificallyintheprogram.AnyI/Ostatementmayincludeanerr= clause(andiostat=clause)tospecifyanalternativebranchtobetakenonerrors(andreturnthe specificerrorcode).Readstatementsmayincludeend=tobranchonend-of-file.Fileposition andthevalueofI/Olistitemsisundefinedfollowinganerror. 2.Implementationdetails Somedetailsofthecurrentimplementationmaybeusefulinunderstandingconstraintson FORTRANI/O. 2.1.Numberoflogicalunits Themaximumnumberoflogicalunitsthataprogrammayhaveopenatonetimeisthe sameastheUNIXsystemlimit,currently20.Unitnumbersmustbeintherange0−19because theyareusedtoindexaninternalcontroltable. 2.2.Standardlogicalunits Bydefault,logicalunits0,5,and6areopenedto‘‘stderr’’,‘‘stdin’’,and‘‘stdout’’respectively.Howevertheycanbere-definedwithanopenstatement.Topreserveerrorreporting,itis anerrortocloselogicalunit0althoughitmaybereopenedtoanotherfile. Ifyouwanttoopenthedefaultfilenameforanypreconnectedlogicalunit,rememberto closetheunitfirst.RedefiningthestandardunitsmayimpairnormalconsoleI/O.Analternativeistouseshellre-directiontoexternallyre-definetheaboveunits.Tore-definedefaultblank controlorformatofthestandardinputoroutputfiles,usetheopenstatementspecifyingtheunit numberandnofilename(see§2.4). Thestandardunits,0,5,and6,arenamedinternally‘‘stderr’’,‘‘stdin’’,and‘‘stdout’’respectively.Thesearenotactualfilenamesandcannotbeusedforopeningtheseunits.Inquirewill notreturnthesenamesandwillindicatethattheaboveunitsarenotnamedunlesstheyhave beenopenedtorealfiles.Thenamesaremeanttomakeerrorreportingmoremeaningful. 2.3.Verticalformatcontrol Simpleverticalformatcontrolisimplemented.Thelogicalunitmustbeopenedforsequentialaccesswithform=’print’(see§3.2).Controlcodes‘‘0’’and‘‘1’’arereplacedintheoutput filewith‘‘\n’’and‘‘\f’’respectively.Thecontrolcharacter‘‘+’’isnotimplementedand,likeany othercharacterinthefirstpositionofarecordwrittentoa‘‘print’’file,isdropped.Novertical formatcontrolisrecognizedfordirectformattedoutputorlistdirectedoutput.

-3-2.4.Theopenstatement Anopenstatementneednotspecifyafilename.Ifitreferstoalogicalunitthatisalready open,theblank=andform=specifiersmayberedefinedwithoutaffectingthecurrentfileposition.Otherwise,ifstatus=’scratch’isspecified,atemporaryfilewithanameoftheform ‘‘tmp.FXXXXXX’’willbeopened,and,bydefault,willbedeletedwhenclosedorduringterminationofprogramexecution.Anyotherstatus=specifierwithoutanassociatedfilenameresultsin openingafilenamed‘‘fort.N’’whereNisthespecifiedlogicalunitnumber. Itisanerrortotrytoopenanexistingfilewithstatus=’new’.Itisanerrortotryto openanonexistentfilewithstatus=’old’.Bydefault,status=’unknown’willbeassumed, andafilewillbecreatedifnecessary. Bydefault,filesarepositionedattheirbeginninguponopening,butseeioinit(3f)foralternatives.Existingfilesarenevertruncatedonopening.Sequentiallyaccessedexternalfilesare truncatedtothecurrentfilepositiononclose,backspace,orrewindonlyifthelastaccessto thefilewasawrite.Anendfilealwayscausessuchfilestobetruncatedtothecurrentfileposition. 2.5.Formatinterpretation FormatsareparsedatthebeginningofeachexecutionofaformattedI/Ostatement.Upper aswellaslowercasecharactersarerecognizedinformatstatementsandallthealphabeticargumentstotheI/Olibraryroutines. Iftheexternalrepresentationofadatumistoolargeforthefieldwidthspecified,thespecifiedfieldisfilledwithasterisks(∗).OnEw.dEeoutput,theexponentfieldwillbefilledwith asterisksiftheexponentrepresentationistoolarge.Thiswillonlyhappenif‘‘e’’iszero(see appendixB). Onoutput,arealvaluethatistrulyzerowilldisplayas‘‘0.’’todistinguishitfromavery smallnon-zerovalue.ThisoccursinFandGformatconversions.ThiswasnotdoneforEand Dsincetheembeddedblanksintheexternaldatumcausesproblemsforotherinputsystems. Non-destructivetabbingisimplementedforbothinternalandexternalformattedI/O.Tab-bingleftorrightonoutputdoesnotaffectpreviouslywrittenportionsofarecord.Tabbingright onoutputcausesunwrittenportionsofarecordtobefilledwithblanks.Tabbingrightoffthe endofaninputlogicalrecordisanerror.Tabbingleftbeyondthebeginningofaninputlogical recordleavestheinputpointeratthebeginningoftherecord.TheformatspecifierTmustbe followedbyapositivenon-zeronumber.Ifitisnot,itwillhaveadifferentmeaning(see§3.1). Tabbingleftrequiresseekabilityonthelogicalunit.ThereforeitisnotallowedinI/Otoa terminalorpipe.Likewise,nondestructivetabbingineitherdirectionispossibleonlyonaunit thatcanseek.OtherwisetabbingrightorspacingwithXwillwriteblanksontheoutput. 2.6.Listdirectedoutput Informattinglistdirectedoutput,theI/Osystemtriestopreventoutputlineslongerthan 80characters.Eachexternaldatumwillbeseparatedbytwospaces.List-directedoutputof complexvaluesincludesanappropriatecomma.List-directedoutputdistinguishesbetweenreal anddoubleprecisionvaluesandformatsthemdifferently.Outputofacharacterstringthat includes‘‘\n’’isinterpretedreasonablybytheoutputsystem. 2.7.I/Oerrors IfI/Oerrorsarenottrappedbytheuser’sprogramanappropriateerrormessagewillbe writtento‘‘stderr’’beforeaborting.Anerrornumberwillbeprintedin[]alongwithabrieferror messageshowingthelogicalunitandI/Ostate.Errornumbers<100refertoUNIXerrors,and aredescribedintheintroductiontochapter2oftheUNIXProgrammer’sManual.Errornumbers ≥100comefromtheI/Olibrary,andaredescribedfurtherintheappendixtothiswriteup.For internalI/O,partofthestringwillbeprintedwith‘‘|’’atthecurrentpositioninthestring.For externalI/O,partofthecurrentrecordwillbedisplayediftheerrorwascausedduringreading -4-fromafilethatcanbackspace. 3.Non-‘‘ANSIStandard’’extensions SeveralextensionshavebeenaddedtotheI/Osystemtoprovideforfunctionsomittedor poorlydefinedinthestandard.Programmersshouldbeawarethatthesearenon-portable. 3.1.Formatspecifiers Bisanacceptableeditcontrolspecifier.Itcausesreturntothedefaultmodeofblankinterpretation.ThisisconsistentwithSwhichreturnstodefaultsigncontrol. Pbyitselfisequivalentto0P.Itresetsthescalefactortothedefaultvalue,0. TheformoftheEw.dEeformatspecifierhasbeenextendedtoDalso.TheformEw.d.eis allowedbutisnotstandard.The‘‘e’’fieldspecifiestheminimumnumberofdigitsorspacesinthe exponentfieldonoutput.Ifthevalueoftheexponentistoolarge,theexponentnotationeord willbedroppedfromtheoutputtoallowonemorecharacterposition.Ifthisisstillnotadequate, the‘‘e’’fieldwillbefilledwithasterisks(∗).Thedefaultvaluefor‘‘e’’is2. Anadditionalformoftabcontrolspecificationhasbeenadded.TheANSIstandardforms TRn,TLn,andTnaresupportedwherenisapositivenon-zeronumber.IfTornTisspecified, tabbingwillbetothenext(orn-th)8-columntabstop.Thuscolumnsofalphanumericscanbe linedupwithoutcounting. Aformatcontrolspecifierhasbeenaddedtosuppressthenewlineattheendofthelast recordofaformattedsequentialwrite.Thespecifierisadollarsign($).Itisconstrainedbythe samerulesasthecolon(:).Itisusedtypicallyforconsoleprompts.Forexample: write(∗,"(’entervalueforx:’,$)") read(∗,∗)x Radicesotherthan10canbespecifiedforformattedintegerI/Oconversion.Thespecifieris patternedafterP,thescalefactorforfloatingpointconversion.Itremainsineffectuntilanother radixisspecifiedorformatinterpretationiscomplete.Thespecifierisdefinedas[n]Rwhere2≤n ≤36.Ifnisomitted,thedefaultdecimalradixisrestored. Inconjunctionwiththeabove,asigncontrolspecifierhasbeenaddedtocauseintegervaluestobeinterpretedasunsignedduringoutputconversion.ThespecifierisSUandremainsin effectuntilanothersigncontrolspecifierisencountered,orformatinterpretationiscomplete. Radixand‘‘unsigned’’specifierscouldbeusedtoformatahexadecimaldump,asfollows: 2000format(SU,16R,8I10.8) Note:Unsignedintegervaluesgreaterthan(2∗∗30-1),i.e.anysignednegativevalue,cannotbe readbyFORTRANinputroutines.Allinternalvalueswillbeoutputcorrectly. 3.2.Printfiles TheANSIstandardisambiguousregardingthedefinitionofa‘‘print’’file.SinceUNIXhasno default‘‘print’’file,anadditionalform=specifierisnowrecognizedintheopenstatement. Specifyingform=’print’impliesformattedandenablesverticalformatcontrolforthatlogical unit.Verticalformatcontrolisinterpretedonlyonsequentialformattedwritestoa‘‘print’’file. Theinquirestatementwillreturnprintintheform=stringvariableforlogicalunits openedas‘‘print’’files.Itwillreturn-1fortheunitnumberofanunconnectedfile. Ifalogicalunitisalreadyopen,anopenstatementincludingtheform=optionorthe blank=optionwilldonothingbutre-definethoseoptions.Thisinstanceoftheopenstatement -5-neednotincludethefilename,andmustnotincludeafilenameifunit=referstoastandard inputoroutput.Therefore,tore-definethestandardoutputasa‘‘print’’file,use: open(unit=6,form=’print’) 3.3.Scratchfiles Aclosestatementwithstatus=’keep’maybespecifiedfortemporaryfiles.Thisisthe defaultforallotherfiles.Remembertogetthescratchfile’srealname,usinginquire,ifyou wanttore-openitlater. 3.4.ListdirectedI/O Listdirectedreadhasbeenmodifiedtoallowinputofastringnotenclosedinquotes.The stringmustnotstartwithadigit,andcannotcontainaseparator(,or/)orblank(spaceortab). Anewlinewillterminatethestringunlessescapedwith\.Anystringnotmeetingtheabove restrictionsmustbeenclosedinquotes("or’). Internallist-directedI/Ohasbeenimplemented.Duringinternallistreads,bytesarecon-sumeduntiltheiolistissatisfied,orthe’end-of-file’isreached.Duringinternallistwrites,records arefilleduntiltheiolistissatisfied.Thelengthofaninternalarrayelementshouldbeatleast20 bytestoavoidlogicalrecordoverflowwhenwritingdoubleprecisionvalues.Internallistreadwas implementedtomakecommandlinedecodingeasier.Internallistwriteshouldbeavoided. 4.Runningolderprograms TraditionalFORTRANenvironmentsusuallyassumecarriagecontrolonalllogicalunits,usuallyinterpretblankspacesoninputas‘‘0’’s,andoftenprovideattachmentofglobalfilenamesto logicalunitsatruntime.ThereareseveralroutinesintheI/Olibrarytoprovidethesefunctions. 4.1.Traditionalunitcontrolparameters Ifaprogramreadsandwritesonlyunits5and6,thenincluding−lI66inthef77command willcausecarriagecontroltobeinterpretedonoutputandcauseblankstobezerosoninputwithoutfurthermodificationoftheprogram.Ifthisisnotadequate,theroutineioinit(3f)canbe calledtospecifycontrolparametersseparately,includingwhetherfilesshouldbepositionedat theirbeginningorenduponopening. 4.2.Preattachmentoflogicalunits Theioinitroutinealsocanbeusedtoattachlogicalunitstospecificfilesatruntime.It willlookfornamesofauserspecifiedformintheenvironmentandopenthecorrespondinglogical unitforsequentialformattedI/O.NamesmustbeoftheformPREFIXnnwherePREFIXis specifiedinthecalltoioinitandnnisthelogicalunittobeopened.Unitnumbers<10must includetheleading‘‘0’’. Ioinitshouldproveadequateformostprogramsaswritten.However,itiswritteninFOR-TRAN−77specificallysothatitmayserveasanexampleforsimilaruser-suppliedroutines.A copymayberetrievedby‘‘arx/usr/lib/libI77.aioinit.f’’. 5.MagnetictapeI/O BecausetheI/Olibraryusesstdiobuffering,readingorwritingmagnetictapesshouldbe donewithgreatcaution,oravoidedifpossible.Asetofroutineshasbeenprovidedtoreadand writearbitrarysizedbufferstoorfromtapedirectly.Thebuffermustbeacharacterobject. InternalI/Ocanbeusedtofillorinterpretthebuffer.TheseroutinesdonotusenormalFOR-TRANI/OprocessinganddonotobeyFORTRANI/Orules.Seetapeio(3f).

-6-6.CaveatProgrammer TheI/Olibraryisextremelycomplexyetwebelievetherearefewbugsleft.We’vetriedto makethesystemascorrectaspossibleaccordingtotheANSIX3.9−1978documentandkeepit compatiblewiththeUNIXfilesystem.ExceptionstothestandardarenotedinappendixB.

-7-AppendixA I/OLibraryErrorMessages ThefollowingerrormessagesaregeneratedbytheI/Olibrary.Theerrornumbersare returnedintheiostat=variableiftheerr=returnistaken.Errornumbers<100aregenerated bytheUNIXkernel.Seetheintroductiontochapter2oftheUNIXProgrammersManualfortheir description. /*100*/"errorinformat" Seeerrormessageoutputforthelocation oftheerrorintheformat.Canbecaused bymorethan10levelsofnested(),or anextremelylongformatstatement. /*101*/"illegalunitnumber" Itisillegaltocloselogicalunit0. Negativeunitnumbersarenotallowed. Theupperlimitissystemdependent. /*102*/"formattedionotallowed" Thelogicalunitwasopenedfor unformattedI/O. /*103*/"unformattedionotallowed" Thelogicalunitwasopenedfor formattedI/O. /*104*/"directionotallowed" Thelogicalunitwasopenedforsequential access,orthelogicalrecordlengthwas specifiedas0. /*105*/"sequentialionotallowed" Thelogicalunitwasopenedfordirect accessI/O. /*106*/"can’tbackspacefile" Thefileassociatedwiththelogicalunit can’tseek.Maybeadeviceorapipe. /*107*/"offbeginningofrecord" Theformatspecifiedalefttabbeyondthe beginningofaninternalinputrecord. /*108*/"can’tstatfile" Thesystemcan’treturnstatusinformation aboutthefile.Perhapsthedirectoryis unreadable. /*109*/"no*afterrepeatcount" Repeatcountsinlist-directedI/Omustbe followedbyan*withnoblankspaces.

-8- /*110*/"offendofrecord" Aformattedwritetriedtogobeyondthe logicalend-of-record.Anunformattedread orwritewillalsocausethis. /*111*/"truncationfailed" Thetruncationofanexternalsequentialfileon ’close’,’backspace’,’rewind’or’endfile’failed. /*112*/"incomprehensiblelistinput" Listinputhastobejustright. /*113*/"outoffreespace" Thelibrarydynamicallycreatesbuffersfor internaluse.Youranoutofmemoryforthis. Yourprogramistoobig! /*114*/"unitnotconnected" Thelogicalunitwasnotopen. /*115*/"readunexpectedcharacter" Certainformatconversionscan’ttolerate non-numericdata.Logicaldatamustbe TorF. /*116*/"blanklogicalinputfield" /*117*/"’new’fileexists" Youtriedtoopenanexistingfilewith "status=’new’". /*118*/"can’tfind’old’file" Youtriedtoopenanon-existentfile with"status=’old’". /*119*/"unknownsystemerror" Shouldn’thappen,but..... /*120*/"requiresseekability" Directaccessrequiresseekability. SequentialunformattedI/Orequiresseek abilityonthefileduetothespecial datastructurerequired.Tabbingleft alsorequiresseekability. /*121*/"illegalargument" Certainargumentsto’open’,etc.willbe checkedforlegitimacy.Oftenonlynondefaultformsarelookedfor.

-9- /*122*/"negativerepeatcount" Therepeatcountforlistdirectedinput mustbeapositiveinteger. /*123*/"illegaloperationforunit" Anoperationwasrequestedforadevice associatedwiththelogicalunitwhich wasnotpossible.Thiserrorisreturned bythetapeI/Oroutinesifattemptingto readpastend-of-tape,etc.

-10-AppendixB ExceptionstotheANSIStandard AfewexceptionstotheANSIstandardremain. 1)Verticalformatcontrol The‘‘+’’carriagecontrolspecifierisnotimplemented.Itwouldbedifficulttoimplementit correctlyandstillprovideUNIX-likefileI/O. Furthermore,thecarriagecontrolimplementationisasymmetrical.Afilewrittenwithcarriagecontrolinterpretationcannotbereadagainwiththesamecharactersincolumn1. Analternativetointerpretingcarriagecontrolinternallyistoruntheoutputfilethrougha ‘‘FORTRANoutputfilter’’beforeprinting.Thisfiltercouldrecognizeamuchbroaderrangeofcarriagecontrolandincludeterminaldependentprocessing. 2)Defaultfiles Filescreatedbydefaultuseofrewindorendfilestatementsareopenedforsequential formattedaccess.Thereisnowaytoredefinesuchafiletoallowdirectorunformattedaccess. 3)Lowercasestrings ItisnotcleariftheANSIstandardrequiresinternallygeneratedstringstobeuppercaseor not.Ascurrentlywritten,theinquirestatementwillreturnlowercasestringsforanyalphanumericdata. 4)ExponentrepresentationonEw.dEeoutput Ifthefieldwidthfortheexponentistoosmall,thestandardallowsdroppingtheexponent characterbutonlyiftheexponentis>99.Thissystemdoesnotenforcethatrestriction.Further, thestandardimpliesthattheentirefield,‘w’,shouldbefilledwithasterisksiftheexponentcan notbedisplayed.Thissystemfillsonlytheexponentfieldintheabovecasesincethatismore diagnostic.