WARNING: This equipment hasbeencertifiedtocomply withthe limits for aClass Bcomputingdevice, pursuant tosubpart Jof Part15of the Federal Communications Commission’srules,whicharedesigned to provide reasonable protection against radioandtelevisioninterference inaresidential installation. Ifnotinstalledproperly, instrict accordancewith themanufacturer’sinstructions, itmay cause suchinterference. Ifyoususpect interference, youcantest this equipment byturning itoff andon.Ifthisequipment does cause interference, correct itbydoinganyofthe following:
•Reorient the receivingantenna or ACplug.
•Change the relativepositions of thecomputer andthe receiver.
This manual containscopyrighted andproprietary information. Nopart ofthispublicationmaybereproduced, storedinaretrieval system, or transmittedinanyformor byanymeans, electronic, mechanical, photocopying, recording or otherwise, without theprior written permission ofCommodore Electronics Limited.
The 1571isaversatile diskdrivethathandlesmultiple diskformatsanddatatransfer rates. Disk formatsrange fromsingle-sided, single-density todouble-sided, doubledensity. The 1571canbeused with avarietyofcomputers, includingtheCommodore128, the Commodore 64, the Plus4, Cl6, andVIC20.
Whenusedwith theCommodore 128Personal Computer, the1571offers the
following features:
•Standard andfastserial datatransferrates—The 1571automaticallyselectstheproper data transfer rate (fast or slow) tomatchthethree operating modesavailable on the Commodore128computer (Cl28mode, C64mode, andCP/Mmode).
•Double-sided,double-density data recording—Providesupto339Kstorage capacityper disk (169K per side).
•Specialhigh-speed burst commands—Thesecommands, usedfor machine language programs, transfer data severaltimesfaster thanthestandard or fast serialrates.
•Chapter 4describes the useoftheDOSShellprogram, whichprovidesyouwithaconvenient alternative waytoexecute disk drive commands.The DOSShellisincluded on the1571test/demo diskette suppliedwith your disk drive.
PARTTWO: ADVANCEDOPERATIONANDPROGRAMMING—isprimarilyintended for usersfamiliar withcomputer programming.PARTTWO issubdividedintosixchapters:
•Chapter 5discussestheconcept ofdatafiles,definessequentialdatafiles,anddescribes howsequential data filesarecreated andusedondisk.
•Chapter 6definesthedifferences between sequentialandrelativedatafiles,anddescribes howrelativedata filesarecreatedandusedondisk.
•Chapter 7describes direct accessdisk commandsasatoolfor advancedusersandillustrates their use.
•Chapter 8centersoninternaldisk commands.Beforeusingthese advancedcommands, youshouldknowhowtoprograma6502chipinmachine language and have accesstoagood memorymapofthe1571.
•Chapter 9provides alistofdisk-relatedkemal ROMsubroutinesandgivesapractical example oftheir useinaprogram.
APPENDICES ATHROUGH G—provide various reference information;for example, Appendix Atellsyou how tosetthe device numberthroughuseoftwoswitchesontheback ofthe drive.
2
Page 11
PARTONE:
BASICOPERATINGINFORMATION
CHAPTER1
HOW TOUNPACK, SETUPANDBEGINUSINGTHE1571
STEP-BY-STEP INSTRUCTIONS
1.Inspect theshipping carton fordamage.Ifyoufindanydamage totheshippingcartonandsuspectthatthediskdrive mayhavebeen affected, contact your dealer.
2.Check the contentsoftheshippingcarton.Packed withthe1571andthisbook, youshouldfindthefollowing:3-prongelectrical powercord, interfacecable, Test/Demodiskette, andawarrantycardtobefilledoutandreturned toCommodore.
4. Connect thepower cord.Check the ON/OFF switchonthe back ofthedrive(seeFigure2)andmake sureit’sOFF. Connect thecordwhereindicated inFigure2.Plug theother endintoagrounded(3-prong) outlet. Don’tturnthepower onyet.
4
Page 13
5.Connect theinterface cable.Make sure your computer andanyother peripheralsareOFF. Plugeither endofthe
interface cableintoeither serial port ontheback ofthedrive (seeFigure2).Plugtheotherendofthe cableintothe back ofthe computer.Ifyouhave another peripheral (printer or extra drive), plugitsinterfacecableintotheremaining serialport onthedrive.
6. Turn ON the power.Witheverything hooked upandthe drive empty, youcanturnonthepower totheperipherals inany order, but turn onthe power tothecomputer last.Wheneverything ison,the drive goes through aself test.Ifalliswell, thegreenlight willflashonce andthe red power-on light willglowcontinuously. Ifthegreenlight continuestoflash, there maybe aproblem. Refer totheTroubleshootingGuide.
OPERATING MODES
To achieve maximum compatabilitybetweenthe1571andother diskdrives, the
1571hastwomodes ofoperation that allowittobeusedinavarietyofsituations.
1541Mode
When you firstturn on the 1571,itpowers upin1541mode. That is, itworksalmost exactly asa1541diskdrive, whichhelps maintain compatabilitywithcertainspecialprograms and copy-protected diskettes.Also, manyloadingroutinesaredependentuponthe 1541-speed internaltiming. However, whenthedrive isinthismode,itcan’ttakeadvantage ofthe special1571features.
1571Mode
In1571mode, the drive cantake advantage ofsuchfeaturesasdouble-sided
diskettes, MFM-format diskettes, fastdatatransfer rates, andburst transfer protocol.The
1571can determine whether or notthe host computer canreceive fastdatatransfer and
transmits accordingly.
ModeSelection
Asmentioned above, the 1571powers upin1541mode. However, itautomatically
shiftsto1571mode uponthe firstofa fastserial transfer initiated bythe host(the
Toinsert adiskette, firstopenthedrive door byrotatingthedoor lever counterclockwise one quarter turn untilitstops, withtheleverparalleltothehorizontal slotinthefront ofthedrive.
Grasp thediskette bytheside opposite thelargeovalaccessslot,andholditwiththelabelup and thewrite-protect notchtotheleft(SeeFigure 3).Nowinsertthediskettebypushingitstraight intotheslot, theaccessslotgoinginfirstandthelabellast.Besure the
cords. Keepsmoke, moisture, dust, andfood offthediskettes. Storediskettesupright intheir paper jackets.
4. Buydiskettes with reinforced hubs.
Although thedrive usuallycentersadiskettecorrectly, itwouldbedifficulttorescue datafromadisketterecordedwithitshuboff-center. Reinforced hubsmakeiteasier for the drive tocenter adiskette.
5.Removeadiskette beforeturning thedrive off.
Ifyoudon’t,youmightlosepart or allthedataonthediskette.
6.Don’tremove adiskette fromthedrive while thegreenlightisglowing.
Thatlight glows whenthe drive isinuse. If youremovethediskette then, youmight lose the information currentlybeingwrittentothediskette.
8
Page 17
USINGPRE-PROGRAMMED (SOFTWARE) DISKETTES
Your softwareuser’sguide shouldlisttheprocedure for loading theprogramintoyourcomputer. Nevertheless, we’ve includedthefollowing procedure asageneralguide.You’llalso use thisprocedure toloadprograms or filesfromyour owndiskettes.For purposesofdemonstration, use theTest/Demodiskette includedwiththediskdrive.
1.Turn on system.
2.Insert diskette.
3.Ifyouare using aVIC20, Commodore 64, or aCommodore128computerinC64
mode, type:LOAD “HOWTO USE”,8Ifyouare usingaPlus/4 or Commodore128inCl28mode, type:DLOAD“HOWTOUSE”
4.Pressthe RETURN key.
5. The following willthenappear onthescreen:
SEARCHING FOR0:HOW TOUSELOADING
READY
I
6.Type:RUN
7. Pressthe RETURN key.
To loadadifferent program or file, simplysubstituteitsname inplace of HOWTOUSEinside the quotation marks.NOTE:The HOWTOUSE programisthekeytotheTest/Demo diskette. WhenyouLOADandRUNit, itprovides instructionsfor usingtherest ofthe programs on thediskette. Tofindout whatprograms areonyour Test/Demo diskette, refer tothe sectionentitled “DIRECTORIES”later inthischapter.
Ifaprogram doesn’tloadorrunproperlyusing theabovemethod,itmaybethatitisa machine language program. But unlessyou’llbedoing advancedprogramming, youneed notknow anything aboutmachine language. Aprogram’suser’sguide shouldtellyouifitiswritteninmachine language. Ifitis, or ifyouarehavingtrouble loadingaparticular program, simply adda,1(comma andnumber 1)attheendofthe command.
9
Page 18
IMPORTANTNOTE
Throughout thismanual, whenthe format for acommand isgiven, itwillfollowaparticular style.Anything that iscapitalized must betyped inexactlyasitisshown (these commandsarelisted incapital lettersfor stylepurposes, DONOTuse theSHIFT keywhen entering thesecommands). Anything inlower case ismoreorlessadefinitionofwhat belongsthere. Anything inbrackets isoptional.
For instance, intheformat for theHEADER command given onthefollowing page, theword HEADER, the capital Iinlid, thecapitalDinDdrive#,andthecapitalUinUdevice#must allbe typed inasis(Ddrive#andUdevice#areoptional).
On the other hand, diskette name tellsyouthat youmust enter aname for thediskette, butitisuptoyou todecide what that namewillbe.Also, theidinlidisleft toyour discretion, asisthe device#inUdevice#.The drive#inDdrive#isalways0 onthe 1571,but couldbe 0or1onadualdisk drive. Beaware, however, thatthereare certainlimitsplaced onwhat youcanuse. Ineach case, thoselimitsareexplained immediatelyfollowingtheformat (for instance, the diskette namecannotbe more than sixteen characters andthe device#isusually8).
Also be suretotype inallpunctuation exactly where andhowitisshowninthe format.
Finally, pressthe RETURNkeyattheendofeachcommand.
HOWTOPREPARE ANEWDISKETTE
Adiskette needs a pattern ofmagnetic groovesinorder forthedrive’sread/write headtofindthingsonit. Thispattern isnot onyour disketteswhenyoubuythem, butyoucanusethe HEADER command orthe NEWcommand toaddittoadiskette. That isknown asformatting thedisk.This isthe command tousewith the Cl28inCl28mode or Plus/4:
HEADER“diskette name ”,lid,Ddrive#[,Udevice#]
Where:“diskette name”isanydesired name for the diskette, upto16characters long(includingspaces),“id”can beanytwo characters aslongastheydon’tformaBASICkeyword(suchasIF or ON) either on their ownor withthecapital Ibeforethem, “drive#”is0.
“device#”is8, unless you have changed itasper instructions inAppendixA(the1571
assumes8even ifyou don’ttypeitin).
The command for theC64, VIC20, orCl28inC64mode isthis:
OPEN15,device#,15,“NEWdrive#:diskettename,id”
CLOSE 15
The device#,drive#,diskette name, andidarethesame asdescribedabove.
The OPENcommand isexplained inthe next chapter.For now, justcopyitasis.
10
Page 19
NOTETOADVANCEDUSERS
Ifyouwant touse variables for thediskette name or id,theformatisasfollows:
C128, Plus/4:HEADER (A$),I(B$),D0
C64:OPEN15,8,15:PRINT#15,“N0:”+A$+B$:CLOSE15
Where:
A$contains the diskette name (16character limit)
B$contains the id(2characters long)
After youformat aparticular diskette, youcanreformatitatanytime. Youcanchange itsname anderaseitsfilesfaster byomitting theidnumberintheHEADERcommand.
DISKETTEDIRECTORY
Adirectory isalist ofthefilesonadiskette.ToloadthedirectoryontheCl28or Plus/4, typethe wordDIRECTORY onablank lineandpresstheRETURNkeyor simplypressthe F3keyonthe Cl28. That doesn’terase anythinginmemory, soyoucancallupadirectoryanytime—evenfromwithinaprogram. The C64directorycommand, LOAD
The 0 ontheleft-hand side ofthetoplineisthedrivenumberof the1571(onadualdiskdriveitcouldbe0 or 1).The diskette name isnext,followedbythe disketteid—bothofwhicharedetermined whenthediskette isformatted.
Note: Direct Accessfiles, also calledRandomfiles,do not automaticallyappear inthedirectory. Theyare covered inChapter 7.
The bottomline ofadirectory showshowmany blocksareavailable foruse. Thisnumberrangesfrom 664 (in1541mode) and1328(in1571mode)onanewlyformatted diskette to0 on onethat iscompletelyfull.
SELECTIVEDIRECTORIES
Byalteringthedirectory LOADcommand, youcancreateakind of“sub-directory”that listsasingle selectedtypeoffile.For example, youcouldrequestalist ofallsequentialdata files(Chapter 5), or one ofalltherelative datafiles(Chapter 6).The format for thiscommand is:
LOAD44$0:pattem =filetype’’,8(for the C64)
where pattern specifiesaparticular group offiles, andfiletypeistheone-letter abbreviationfor the typesoffileslisted below:
P=Program
S=Sequential
R=Relative
U=User
The command for theCl28andPlus/4 isthis:DIRECTORY“pattern=filetype”
You canuse special pattern-matchingcharacters toloadaprogramfromapartialname ortoprovide the selective directories describedearlier.
The twocharacters used inpatternmatchingare the asterisk (*)andthequestion mark (?). They act something like awildcardina game ofcards. The difference between the twoisthat the asterisk makes allcharacters inandbeyond itsposition wild, while thequestion markmakesonly itsownposition wild.Here aresome examples andtheir results:
LOAD“0:*”,8loads the firstfileonthediskette (C64andCl28inC64mode).
DLOAD loads the firstfileonthe diskette (Plus/4and Cl28inCl28mode).
SPLAT FILES
One indicator youmayoccasionallynoticeon adirectoryline, after youbeginsavingprograms andfiles, isanasterisk appearing just beforethefiletypeofafilethatis0blocks long.This indicates the filewasnotproperlyclosedafteritwascreated, and thatitshould notbe relied upon.These “splat”filesnormally needtobeerasedfromthediskette andrewritten. However, donotusetheSCRATCHcommandtoget ridofthem. They canonlybe safely erased bythe VALIDATEor COLLECT commands.One oftheseshould normally beused whenever asplat fileisnoticedonadiskette.Allofthese commands are described inthe following chapters.
There are two exceptions tothe abovewarning:one isthatVALIDATE andCOLLECT cannot beusedonsome diskettesthat include direct access(random) files(Chapter 7). The other isthatiftheinformationinthesplat filewascrucialandcan’tbereplaced, thereisawaytorescue whatever part ofthefilewasproperlywritten. Thisoption isdescribed inthe nextchapter.
13
Page 22
CHAPTER 2
BASIC2.0COMMANDS
This chapter describes thediskcommands usedwiththeVIC20, Commodore64or the Commodore 128computer inC64mode. These areBasic2.0commands.
You send command datatothedrive through somethingcalled thecommand channel. The firststepistoopenthechannel withthefollowingcommand:
OPEN15,8,15
The first15isafilenumber or channel number. Although itcould beanynumberfrom 1to255, we’lluse 15because itisusedtomatch thesecondaryaddressof15,whichisthe address ofthe command channel. The middle numberistheprimary address, better known asthe device number. Itisusually 8,unless youchange it(seeAppendix A).
Oncethe channelhasbeenopened, usethePRINT#commandtosendinformationtothe diskdrive andthe INPUT#command toreceive information fromthedrive.Youmust close the channel with the CLOSE15command.
The followingexamplesshowtheuse ofthecommandchanneltoNEWanunformatted disk:
Youcan combine the firsttwostatementsandabbreviatetheNEWcommandlike
this:
OPEN 15,8,15/‘Ndrive#:diskname,id”
Ifthecommand channel isalready open, youmustusethe following format (tryingto
open a channelthatisalreadyopenresultsina“FILE OPEN”error):
PRINT#15,‘‘Ndrive#:diskname,id’’
ERROR CHECKING
InBasic2.0,whenthe greendrive lightflashes, youmustwriteasmallprogramtofindout what the error is.This causes youtoloseanyprogramvariablesalreadyinmemory. The followingistheerror check program:
This assumes file15wasopened earlier intheprogram, andthatitwillbeclosedat
the endoftheprogram.
The subroutine readstheerror channelandputstheresultsintothenamedvariables—EN(Error Number), EM$(ErrorMessage), ET(Error Track), andES(Error Sector). Ofthe four, only EM$hastobeastring. Youcouldchooseothervariablenames, althoughthesehave become traditional forthisuse.
Because thisisasubroutine, youaccessitwiththeBASICGOSUBcommand, either inimmediate modeor fromaprogram. The RETURNstatement inline60010willjump back toimmediate modeor the next statementinyour program, whicheverisappropriate.
BASICHINTS
Hint #1:Itisbest toopenfile15once attheverystartofaprogram, andonlycloseitat
the endoftheprogram, after allother fileshave alreadybeenclosed. Byopeningitonceatthe start, the fileisopenwhenever neededfor diskcommandselsewhere intheprogram.
Hint#2:IfBASIChalts withanerror whenyouhave filesopen, BASICabortsthemwithout closing them properlyonthedisk.Toclosethemproperlyonthedisk, youmusttype:
CLOSE 15:OPEN15,8,15,“I”:CLOSE15
Thisopensthe command channel andimmediatelyclosesit,alongwithallother disk
files.Failure toclose adiskfileproperly bothinBASICandonthediskmayresultinlosing the entire file.
Hint #3:One diskerror messageisnot alwaysanerror.Error 73, “CBMDOS3.0
1571”willappear ifyouread the disk error channelbefore sendinganydiskcommandswhenyou turn on yourcomputer. ThisisahandywaytocheckwhichversionofDOSyouareusing. However, ifthismessage appearslater, after otherdiskcommands, itmeans
there isamismatch between the DOSusedtoformat your disketteandtheDOSinyour
where“drive #:”isthedrive number, 0onthe1571;“filename”isanyvalidfilename up to14characters long (leavingtwo for thedrive numberandcolon);“device#”isatwodigit device number, normally 08(theleading 0isrequired); andthe addressestobesaved are given inHexadecimalbutwithoutaleading dollar sign($).Notethe endingaddress listed must beonelocationbeyond thelast location tobe saved.
EXAMPLE:
Here istherequired syntax toSAVE acopy of“DOS5.1”
.S“0:DOS5.1”,08,CC00,D000
SAVEWITHREPLACEOPTION
Ifa filealready exists, itcan’tbesavedagainwiththesamename because thediskdriveonly allowsonecopy ofanygivenfilename per diskette.Itispossible toget aroundthisproblemusing the RENAME andSCRATCHcommandsdescribedlater.However, if allyou wish todo isreplace aprogramor datafilewitharevisedversion,another command ismore convenient. KnownasSAVE-WITH-REPLACE, or @SAVE, thisoptiontellsthediskdrive toreplaceanyfileitfindsinthediskettedirectory withthe samename, substituting the newfilefor theoldversion.
16
Page 25
FORMAT FORSAVE WITH REPLACE:
SAVE“@Drive#:filename”,device #
where allthe parameters are asusualexcept for addingaleading“at”sign(@.)The “drive#:”isrequired here.
EXAMPLE:
SAVE“@0:REVISEDPROGRAM”,8
The actual procedure isthat the newversion issavedcompletely, thenthe oldversion iserased. Because itworks thisway, there islittledanger adisaster suchashavingthepowergoing offmidway through theprocesswoulddestroyboththeoldandnewcopiesofthe file.Nothinghappens tothe oldcopy until afterthenewcopyissavedproperly.
Caution—donotuse @SAVE onanalmost-fulldiskette.Onlyuse itwhenyou have enough room on the diskette tohold asecondcompletecopyoftheprogram being replaced. Due tothe way@SAVEworks, both theoldandnewversionsofthe fileareondisk simultaneously atone point, asawayofsafeguardingagainst lossoftheprogram. Ifthereisnot enough roomleft ondiskette toholdthat secondcopy, onlyasmuchofthe newversion willbe savedasthere isstillroomfor.Afterthecommandexecutes, alook atthe directory willshowthe newversionispresent, butdoesn’toccupyenough blocks tomatchthe copyinmemory. Unfortunately, theVERIFYcommand(seebelow) willnotdetect thisproblem, because whatever wassavedwillhave beensavedproperly.
VERIFY
Although notasnecessarywithadisk drive aswithacassette, BASIC’sVERIFY command can beused tomake doubly certainthat aprogramfilewasproperlysavedtodisk. Itworksmuch likethe LOADcommand, except that itonlycompareseachcharacter inthe program against theequivalent character inthecomputer’smemory, insteadofactually being copied intomemory.
Ifthe disk copyofthe programdiffersevenatinybitfromthecopyinmemory,
Naturally, there’snopoint intryingtoVERIFYadisk copyofaprogramafter theoriginal isnolonger inmemory. Withnothing tocompare to, anapparenterror willalwaysbe announced, even though thediskcopy isalwaysandautomaticallyverifiedasitiswritten tothe diskette.
FORMAT FORTHE VERIFY COMMAND:
VERIFY “drive#-.pattern”,device#,relocateflag
where“drive#:”isanoptional drive number, “pattern”isanystring expression thatevaluates toafilename, withor without pattern-matching characters, and“device#”isthe disk device number, normally 8.Iftherelocateflagispresent andequals 1,the file
willbeverifiedwhereoriginally saved, rather thanrelocated intotheBASICtext area.
17
Page 26
Auseful alternate formofthe command is:
VERIFY“*’\device#
It verifiesthelastfilesusedwithout havingtotypeitsname ordrive number. However, itwon’twork properly after SAVE-WITH-REPLACE, because thelastfileusedwasthe one deleted, andthe drive willtrytocompare the deletedfiletotheprograminmemory. Noharm will result, but “VERIFY ERROR”willalwaysbeannounced.Touse VERIFYafter@SAVE, includeatleast part ofthefilename thatistobeverifiedinthe pattern.
One other note about VERIFY—whenyouVERIFYarelocatedBASICfile, anerror will nearly alwaysbe announced, due tochanges inthelinkpointers ofBASICprogramsmade during relocation. Itisbest toVERIFY filessavedfromthe same type ofmachine, andidentical memory size. For example, aBASICprogramsavedfromaPlus/4can’tbeverified easilywithaC64, even whenthe programwouldwork fineonboth machines. This shouldn’t matter, astheonly time you’llbe verifyingfilesonmachines other thantheone whichwrote themiswhen youarecomparing twodiskfilestoseeiftheyarethesame. This isdone byloading one andverifyingagainsttheother,andcanonlybedoneon the same machine and memorysizeastheone onwhichthe fileswere firstcreated.
SCRATCH
The SCRATCH command allows youtoerase unwantedfilesandfreethe spacetheyoccupied for use byother files.Itcanbe usedtoeraseeither asinglefileor severalfilesatonce via pattern-matching.
FORMATFORTHESCRATCHCOMMAND:
PRINT#15,“SCRATCH0:pattem’’
or abbreviate itas:
PRINT #15,“S0:pattem ’’
“pattern”can beanyfilename or combinationofcharacters andwild-cardcharacters.Asusual, itisassumed the command channel hasalreadybeen openedasfile15.Although notabsolutely necessary, itisbest toincludethedrive numberinSCRATCHcommands.
where“newname”isthe name youwant thefiletohave, and“oldname”isthename ithasnow. “newname”maybeanyvalidfilename, upto16characters inlength. Itisassumed you have already openedfile15tothecommandchannel.
One caution—besure thefileyouarerenaming hasbeen properlyclosedbeforeyourename it.
EXAMPLES:
Just beforesaving anewcopyofa“calendar”program, youmight type:
PRINT#15,“R0:CALENDAR/B ACKUP =CALENDAR’’
Or tomove aprogram called “BOOT,”currentlythefirstprogramonadiskette tosomeplace else inthedirectory, youmight type:
PRINT#15/‘R0:TEMP =BOOT’’
followed byaCOPY command (described later),.which turns“TEMP”intoanewcopyof“BOOT,”andfinishingwithaSCRATCHcommandtoget ridoftheoriginalcopyof“BOOT.”
20
Page 29
RENAMING AND SCRATCHING TROUBLESOME FILES(ADVANCED USERS)
Eventually, you mayrunacrossafilewhichhasanoddfilename,suchasacomma byitself(“,”)orone that includes aShiftedSpace (aShiftedSpacelooksthe same asaregular space, but ifafilewithaspace initsname won’tloadproperlyandallelse iscorrect, it’sprobably aShifted Space). Or perhapsyouwillfindone thatincludesnonprinting characters. Anyofthesecanbetroublesome. Comma files, for instance, areanexception tothe rule that notwofilescanhave thesame name.Sinceitshouldn’t bepossible tomakeafilewhose name isonlyacomma, thedisk never expectsyoutodoitagain.
Files with aShifted Space intheir name canalsobe troublesome, because thediskinterprets the Shifted Space assignalingtheendofthefilename, andprintswhatever followsafter the quotationmarkthat markstheendofaname inthe directory.Thistechnique canbeuseful byallowing youtohave alongfilename, andmakingthediskrecognize asmall part ofitasbeingthe same asthewholethingwithout usingpattern- matching characters.
Inany case, ifyouhave atroublesome filename,youcanusethe CHR$() functiontospecify troublesome characters without typing themdirectly. ThismayallowyoutobuildthemintoaRENAME command. Ifthisfails, youmayalsousethepattern-matching characters inaSCRATCH command. Thisgivesyouawaytospecifythename without using the troublesome characters at all, but alsomeanslossofyour file.
For example, ifyouhave managed tocreateafilenamed ““MOVIES”,withanextra quotation markatthe front ofthefilename, youcanrename itto“MOVIES”usingthe CHR$() equivalent ofaquotation markintheRENAME command:
PRINT#15,“R0:MOVIES=”+CHR$(34)+“MOVIES”
The CHR$(34) forces aquotationmarkintothecommandstringwithout upsettingBASIC. The procedure for afilename thatincludesaShiftedSpace issimilar,but usesCHR$(160).
Incases where even thisdoesn’twork,for example, ifyour diskette contains acomma file, (one named “,”)youcanget ridofitthisway:
PRINT#15,“S0:?”
Thisexample deletes allfileswith one character names.
Depending on theexact problem, youmayhave tobeverycreative inchoosing pattern-matching characters thatwillaffect onlythedesiredfile,andmayhave torename other filesfirsttokeep themfrombeingscratched.
The COPY command allowsyoutomake asparecopy ofanyprogramor fileona
diskette. Onasingle drive likethe1571,thecopymust beonthesamediskette, whichmeans itmustbegivenadifferent name fromthefilecopied. It’salsousedtocombine up
21
Page 30
tofour sequential datafiles(linkingthefilesone toanother, endtoendinachain). Filesare linked inthe order inwhichtheyappear inthecommand.The source filesandotherfileson the diskette arenotchanged. Filesmust be closed before theyarecopied or linked.
After renaming afilenamed “BOOT”to“TEMP”inthe lastsection’sexample, you can use theCOPY command tomake asparecopyoftheprogramelsewhere onthediskette, under theoriginalname:
PRINT#15,“C0:BOOT =TEMP”
After creating several smallsequentialfilesthat fiteasilyinmemoryalongwithaprogram we are using, youcanuse theconcatenate optiontocombine theminamaster
file, even ifthe result istoobigtofitinmemory. (Besureitwillfitinremainingspace on
the diskette—itwillbe asbigasthesumofthesizesofthefilesinit.)
PRINT#15,“C0:A-Z=A-G,H-M,N-Z’’
22
Page 31
NOTE: Dual drivesmakefuller useofthiscommand, copyingprograms fromonediskette toanother inasingle-diskunit. Todothat onthe 1571,check your Test/Demo diskette tofindthe programsthat youneedor use theDOSShelldescribedinChapter 4.
VALIDATE
The VALIDATE command recalculatestheBlockAvailabilityMap(BAM) of thecurrent diskette, allocating onlythosesectorsstillbeingusedbyvalid, properly-closed filesandprograms. Allother sectors(blocks) areleft unallocated andfreefor re-use, andallimproperlyclosed filesareautomaticallyscratched. Thisbriefdescription ofitsworkingsdoesn’tindicate either thepower or thedanger oftheVALIDATEcommand. Itspower isinrestoringtogoodhealthmanydisketteswhose directories or blockavailability maps have become muddled.Anytime theblocksusedbythefilesonadisketteplustheblocksshown asfreedon’tadduptothe664(in1541mode) or 1328(in1571mode)
available onafreshdiskette, VALIDATEisneeded,withoneexceptionbelow. Similarly,
(*)next toitsfiletypeinthedirectory, thatdiskette needstobevalidated. Infact, butfor the oneexception, itisagoodidea toVALIDATEdiskettes wheneveryouaretheleastbitconcerned about their integrity.
The exception isdiskettes containing Direct Accessfiles,asdescribed inChapter7.
Most direct access (random) filesdonotallocatetheir sectorsinawaytheVALIDATEcommand can recognize. Thus, usingVALIDATEonsuchadiskette mayresultinun
allocating alldirect accessfiles, with lossofalltheir contentswhenother filesareadded.
Unlessspecifically instructed otherwise, never useVALIDATEonadiskette containing
direct access files.(Note:these arenotthesameastherelative filesdescribedinChapter
Because thisisasubroutine, youaccessitwith theBASICGOSUBcommand, either inimmediate mode or fromaprogram. The RETURN statementinline60010 willjumpback toimmediate modeor thenext statementinyour program, whichever isappropriate.
SAVE
This command willsave aprogramor filesoyoucanreuse it.The diskette must beformatted before youcansave ittothat diskette.
FORMAT FORTHE SAVECOMMAND
DSAVE “filename”[,Ddrive#][,Udevice#]
This command willnot work incopying programs thatare not writteninBASIC. Tocopy these machine language programs, youcanuse theBSAVE commandor thebuilt-in
Monitor Scommand.
25
Page 34
FORMAT FORTHE BSAVE COMMAND
BSAVE “filename”[,Ddrive#][,Udevice#][Bbank#]
[,Pstarting address] [TOPending address+1]
wherethe usual optionsarethesame andbank#isoneofthe16banksofthe Cl28.Theaddressestobe savedare givenindecimal.Notethattheendingaddressmustbe1location beyond the last locationtobesaved.
To accessabuilt-inmonitor, typeMONITOR. Toexitamonitor, typeXalone ona
where“drive #:”isthedrivenumber, 0onthe1571;“filename”isanyvalidfilenameup to14characters long (leaving 2forthedrive numberandcolon); “device #”isatwodigit device number, normally 08onthe1571(the leading0isrequired); andtheaddressestobesavedare given inHexadecimal(base16,)but without aleading dollarsign (for the Plus/4). OntheCl28, the addressesneednot beinHexidecimal.Note thatthe ending addresslisted mustbe 1location beyondthelastlocationtobesaved.
SAVE WITHREPLACE
Ifafilealready exists, itcan’tbe savedagainwiththesamename becausethe diskdriveallows onlyone copyofanygivenfilename per diskette.Itispossibletogetaroundthisproblem using the RENAME andSCRATCHcommands describedlater inthischapter. Ifallyou wish todoisreplace aprogramor data filewitharevisedversion, another command ismoreconvenient. Known asSAVEWITH REPLACE, or @SAVE thisoptiontellsthe diskdrive toreplaceanyfileitfindsinthediskette directorywiththesame name, substituting the newfilefor theoldversion.
FORMAT FORSAVEWITHREPLACE
DSAVE “@file name”[,Ddrive#][,Udevice#]
The actual procedure isthis—thenewversionissavedcompletely, thenthe oldversion isscratched and itsdirectoryentryalteredtopoint tothenewversion. Becauseitworks thisway, thereislittledanger adisaster suchashavingthepower goingoffmidwaythrough the process would destroy boththeoldandnewcopiesofthefile.Nothing happens tothe old copy until after thenewcopyissavedproperly.
Caution—do notuse @SAVE onanalmost-fulldiskette.Only useitwhenyouhaveenough roomon thediskette toholdasecondcompletecopyoftheprogrambeing replaced. Due totheway@SAVE works, boththeold andnewversionsofthefileareondisksimultaneously atone point, asawayofsafeguarding againstlossoftheprogram. Ifthere isnotenough roomleft ondiskette toholdthesecondcopy, onlyasmuchofthe new
26
Page 35
version will be savedasthere isstillroomfor.After thecommand iscompleted, alookatadirectory willshowthenewversionispresent, butdoesn’toccupyenoughblockstomatch the copy inmemory.
DVERIFY
Thiscommand makesabyte-by-byte comparison oftheprogramcurrently inmemory against aprogramondiskette. ThiscomparisonincludestheBASIClinelinks, whichmaybedifferent for different types ofmemoryconfigurations. Whatthismeansisthataprogramsaved todiskonaC64andreloadedintoaCl28wouldn’tverifyproperlybecause the linelinkspointtodifferentmemorylocations. Ifthediskcopyoftheprogramdiffers atallfromthecopy inmemory, a“VERIFYERROR”willbedisplayed. Thisdoesn’tmean either copyisbad, butif theyweresupposedtobeidentical, there isaproblem.
FORMAT FORTHE DVERIFY COMMAND
DVERIFY “filename”[,Ddrive#][,Udevice#]
The following versionofthecommandverifiesafilethatwasjustsaved:
DVERIFY
Thiscommand won’tworkproperlyafterSAVE-WITH-REPLACE, because thelastfileusedwastheone deletedandthedrivewilltrytocompare thedeleted filetotheprograminmemory. Noharmwillresult, but“VERIFYERROR”willalwaysbeannounced. Touse DVERIFY after @SAVE, include atleastpart ofthefilename thatistobeverifiedinthepattern.
COPY
The COPY command allowsyoutomakeasparecopyofanyprogramor fileona
diskette. However, onasingle drive likethe1571,thecopymustbeonthesamediskette,
The SCRATCH command allowsyoutoeraseunwanted programs andfilesfromyour diskettes, andfreeupthespace theyoccupied for usebyother filesandprograms.Itcanbeusedtoeraseeither asinglefile,or severalfilesatonceviapattern-matching.
FORMAT FORTHE SCRATCH COMMAND
SCRATCH “pattern”[,Ddrive#][,Udevice#]
Where, “pattern”isanyvalidfilename or pattern-matching character.
Youwillbeaskedasaprecaution:
ARE YOUSURE? ■
IfyouARE sure, simply pressYandRETURN.Ifnot, pressRETURNalone or typeanyother answer, andthecommand willbecanceled.
28
Page 37
The number offilesthatwerescratched willbe automaticallydisplayed. For example, ifyour diskette contains programfilesnamed“TEST,”“TRAIN,”“TRUCK,”and“TAIL,”youmayscratchallfour, alongwithanyother filesbeginningwiththeletter “T,”byusing the command:
SCRATCH “T*”
andifthe four listed werethe onlyfilesbeginning with“T”,youwillsee:
SCRATCH isapowerfulcommand andshouldbeusedwithcaution tobesureyoudeleteonlythefilesyoureallywant erased. Whenusing itwith apattern, wesuggestyoufirstuse the same patterninaDIRECTORY command, tobe sureexactly whichfileswillbedeleted. That wayyou’llhave nounpleasant surpriseswhenyouusethesamepatternintheSCRATCH command.
Recovering fromaSCRATCH
Ifyouaccidentally SCRATCH afileyoushouldn’thave, there isstillachance of saving it.LikeBASIC’sNEWcommand, SCRATCHdoesn’treallywipe out afileitself;itmerely clears the pointers toitinthediskette directory.There maybean“Unscratch”program on your Test/Demo diskette.
RENAMING AND SCRATCHING TROUBLESOMEFILES (ADVANCED USERS)
Eventually, youmayrunacrossafilewhichhasacrazyfilename,suchasacomma by itself(“,”)orone that includes aShiftedSpace. Orperhapsyouwillfindone thatincludes nonprintingcharacters. Anyofthese canbe troublesome. Comma files,for instance, are anexception totherulethat notwofilescanhave thesamename.Sinceitshouldn’tbe possibletomake afilewhosename isonlyacomma, thedisknever expectsyou todoitagain.
Fileswith aShifted Space intheir name canalsobetroublesome, because thediskinterpretsthe Shifted Space assignaling theendofthefilename, andprintswhatever followsafter thequotation mark thatmarksthe endofaname inthedirectory.Thistechnique canbeuseful byallowing youtohave alongfilename, andmakingthe diskrecognize asmallpart ofitasbeing thesameasthewholethingwithout usingpattern- matching characters.
30
Page 39
Inanycase, ifyouhaveatroublesome filename,youcanusetheCHR$() functiontospecify troublesome characters without typing themdirectly.ThismayallowyoutobuildthemintoaRENAME command. Ifthisfails,youmayalsousethepattern-matching characters discussed for aSCRATCH command. Thisgivesyoua-wayto specifythename without using the troublesome characters atall, butalsomeanslossofyour file.
For example, ifyouhave managed tocreateafilenamed““MOVIES”,withanextra quotation markatthe front ofthefilename, youcanrename itto“MOVIES”usingthe CHR$() equivalent ofaquotationmarkintheRENAME command:
Example:
RENAME(CHR$(34) +“MOVIES”)TO“MOVIES”
The CHR$(34) forcesaquotation markintothecommandstringwithout upsettingBASIC. The procedure forafilename thatincludesaSHIFT-SPACE issimilar,but usesCHR$(160).
Incases where eventhisdoesn’twork, for example, if your diskettecontainsacomma file, (one named “,”)youcanget ridofitthisway:
The COLLECT command recalculatestheBlockAvailabilityMap(BAM) ofthecurrent diskette, allocating onlythosesectorsstillbeingusedbyvalid, properlyclosedfilesand programs. Allother sectors(blocks) areleft unallocatedandfreefor reuse, andallimproperlyclosed filesare automaticallyscratched. However, thisbrief description ofCOLLECT doesn’tindicate either thepower or thedanger ofthecommand. Itspower isinrestoring togoodhealthmanydiskettes whose directories or BlockAvailabilityMapshavebecome muddled.Anytime theblocksusedbythefilesonadisketteplustheblocks
shownasfreedon’tadduptothe664(in1541mode) or 1328(in1571mode) available onafresh diskette, COLLECT isneeded(withone exceptionbelow).Similarly,anytime a
diskette containsanimproperlyclosedfile(splatfile),indicatedbyanasterisk(*)next to
itsfiletype inthe directory, that diskette needstobecollected.Infact,butfor theone
about their integrity. Just note thenumber ofblocksfreeinthediskette’sdirectory beforeandafter using COLLECT. Ifthe totalsdiffer, therewasindeedaproblem, andthe
There isnoBASIC7.0commandfor initializing, sorefer toChapter 2for theBASIC
2.0INITIALIZEcommand.
32
Page 41
CHAPTER 4DOSSHELL
The DOSShell isaprogram thatprovidesyouwithanalternate waytoexecute diskdrivecommands. Promptingmessages take youstep-by-stepthrougheachoperation, making the use ofthe 1571easier andmoreunderstandable.
The Shell isautomaticallyloadedwhenyouinsert thediskette,thenturnonor reset
the computer. Youcan enter or exittheShellbypressingtheFIkey.
LANGUAGE SELECTION
The Shell displays itsmessages inanyone offour languages:English, French,German,andItalian.Whenyouenter theShell, eachlanguage appears, inturn, onthescreen for about sixseconds.Tochoose one, pressthespace bar whenitappearsonthescreen. Youcan skiptothenext language without waitingthesixsecondsbypressingtheCRSR-down key.
NOTE:The DOSShellcanbe usedin40-column or 80-columnmode.The onlydifference isachangeinthelayout ofthescreen. Youcanswitchthe screensizebyfirstpressing the ESCkeyandthenpressing theXkey. Thismust bedone beforeyou selectafunctionfromtheprimarymenuscreen(seebelow).
PRIMARY MENU SCREEN
After alanguage ischosen, theprimarymenuscreenappears. Tochoose afunction,
use the CRSRkeystopositionthecursor onthatfunctionthenpresstheSPACE BAR.
DISK/PRINTER SETUP
Within the Shell thereare twodrives:AandB.Theyarecalledlogicaldrivesbecause theyreside only within the Shell. Youcansetthemtorepresent asingle diskdrive unit, two single units, or adual drive unit. Assuming youhaveasingleunit, theusualsettingsfor Aand Bwould showadevice#of8andadrive#of0.Those arethe default settings(inother words, whenyou firstenter theShell, theDisk Setupissuchthatitrepresentsa
single unit). Withtwo singleunits, youwouldchange thedevice#ofone ofthedrives. The drive#scanstaythesame.Withadualdriveunit, youwouldchange thedrive#ofone ofthe drives.
Tochange the device number oftheactualdrive (thephysicaldrive), positionthecursoron the ‘CHANGE DISK DEVICE#’lineandpresstheSPACE BAR. Amessage thenappears on thescreenguiding youthrough thestepstochange the device#.Ifyouchange your mind before completing thesteps,presstheSTOPorF5keystocancel thedevice#change. F5returnsyoutothelogicaldrive selectionsandSTOPreturns youtothe primary menuscreen.
Changing the device#locks inallcurrentparametersinthisfunction.
NOTE:Unlessthe DiskSetup issetfor asingledrive unit,whenyouchooseanyof the following functions, aquestion appearsonthescreenaskingyouwhichdrive youwant to use. Indescribing thesefunctions, we’llassume thatyouhave asingledisk. Ifyou havemore than one, thenyou’llhave toprovide the appropriateanswer tothat question throughthe use oftheCRSRkeysandSPACE BAR.
RUNAPROGRAM
This functionautomaticallyloadsandrunsaprogramfilethat youchoosefromafilelistshown on thescreen (forthisfunction thefilelist contains onlyprogramfiles). UsetheCRSR keystopositionthecursor over thedesiredfile,thenpressthe SPACEBARtochoose that file.Ifyou change your mind, pressthe F5keytoun-select thefile.PresstheF7key toload and run it.Ifyoupressthestopkeybeforetheloadingiscomplete, thefunction iscancelled.
You canprint outthe filelist, whenever it’sdisplayed for afunction, bypressingthe
F3key. Make sure your printer isturnedonandthepaper isatthetopofapage.
Note thatsome machine language programs won’truninthe Shell.
FORMATADISK
Whenyouselect this function, amessage appearsonthescreentelling youtoinsert ablank disk intothe drive. After youdothat, presstheSPACEBARandthe Shellchecks toseeifthe diskhasalready beenformatted. Ifithas, thediskheader informationisdisplayed on the screenasaprecaution thatthere maybefilesonthedisk. Toproceedwithformatting, eitherenter anewdiskname or accept theoldone andpressRETURN.If the disk waspreviously formatted, itretainsitsoldIDcode.Ifnot,theShellrandomlygenerates one. You can enter your ownIDcode byentering acomma andtwo-digitIDcode asthe lastthreecharacters ofthedisk name.
CLEANUPADISK
This functionenables youtovalidate theBlockAvailabilityMapofadisk(seetheVALIDATE command inchapter 2or the'COLLECT commandinchapter 3).
34
Page 43
COPYADISK
Use thisfunction tomake backupsofyour diskettes.The diskdrive setup(drivesAandB)determines whattypeofcopyisperformed: singleunit, dualdrive, or twosingleunits.
DualDriveorTwo Unit Copy
The Shell asksyoufromwhichdrive youwant tocopy(useCRSRkeysandspacebar toselect Aor B).Insert the original disk intothatdriveandthecopydiskintotheotherdrive andpresstheSPACEBAR. PresstheSTOPkeytocancelthisfunction. The F5keyor SPACE BARcanbeusedtoretryadiskoperationifanerror occurs.
SingleDriveCopy
The Shell displays thefollowing warning message:‘PROGRAMSINMEMORYWILL BEDESTROYED’.PresstheSTOPor F5keystocancelthefunctionatthispoint.Pressthe SPACE BARtocontinue.
Throughout thisfunction youwillalternatelyinserttheoriginalandcopydisksaccordingtoprompts fromtheShell.Ittakesfromonetofour swapstocompletethecopy. The firsttime youinsert thecopy disk, itisformattedwiththesamediskname astheoriginal disk, but adifferent IDcode isgenerated. Then, each timeyouinsert adisk, itsIDcode ischecked tomake surethatit’sthecorrect disk. Ifit’snot,anerror message isdisplayed onthescreen.Ifthathappens, presstheSPACEBARor theF5keytoreturntothelast-useddiskswapping prompt.
Thisfunction makescopies ofselectedfiles,thetypeofcopy isdetermined bytheDiskDrive Setup. Once youselectthedrivefromwhichthefileswillbecopied, the filelistisdisplayed soyoucanselect thefilesusingtheCRSRkeysandSPACEBAR. You
can“scroll”thelistupor downusingtheCRSRkeys.
Once youposition thecursornext toafileyouwant tocopy, presstheSPACE BAR.Youcan ‘unselect’anyfile(s)bypositioningthecursor onthefilenameandpressingtheF5key.
PresstheF7keywhenyou’vecompleted fileselection. The Shellthenasksyouifitis“OK TO COPY FILE-LIST:NY”.Ifyouanswer Yes, thefunctioncontinues.Ifyouanswer No(thedefault answer), theShellreturnstofileselectionwithallpreviousselections intact.
After youanswer the‘OKTOCOPY’question, themessages‘INSERT COPYDISKINTODRIVE: X’and ‘THENPRESSSPACE’aredisplayed. After youdothat, themessage ‘WANTTO FORMAT THE COPYDISK:NY’isdisplayed(unless,how
ever, the copydisk hasnever beenformatted, inwhichcasetheShellautomaticallydoesit
without askingyou). The default answer isNo. Ifyouanswer Yes,the‘FORMATA
35
Page 44
DISK’function begins atthepointwhere youareaskedtoenter anewdisk name for formatting.
Whether youanswer Yesor Nototheformatting question, theShellcheckstheavailable space onthecopydiskagainst thetotalsizeoftheselectedfile(s).Ifthe copydisk can’tholdallthefiles,awarning isdisplayed andyoucanpressthe STOPkeytocancel the function or press theSPACE BARtocontinue.
NOTE: For anytypeoffilecopy, ifthenext filetobecopiedwon’tfitonto thecopy disk, thefollowing message isdisplayed:‘COPYDISKFULL—ANOTHERDISK: YN’.Iftheanswer isNo(thedefault answer), thecopyisterminated. IfYes, the function returnstothe‘INSERT COPYDISK’message.
This function restores one or morefilesthathavebeen deleted. Afilelistofonlydeleted filesisdisplayed onthescreenandyouagainusethetheCRSRkeysandSPACEBARtoselect thefile(s)toberestored.
After youselect afile,theShellchecks toseeifitcanberestored without corrupting
other files.Ifnot, the message ‘CANNOT RESTOREFILE:filenameid’isdisplayed. If
everything’sOK, the fileselectioncontinues.
36
Page 45
Aseach fileisselected, youareaskedto‘CHOOSEFILE-TYPE: SEQPRGUSR\Use the CRSRkeysandSPACE BARtochoose.Relativefilesareautomaticallyidentified,soyouneedn’tspecifythattype.
You can ‘unselect’anyfile(s)bypositioning the cursor onthefilenameandpressing
the F5key.
Press the F7keywhenyou’vecompletedfileselection. The Shellthenasksyouif itis“OK TORESTORE FILE-LIST:NY”.Ifyouanswer Yes, the functioncontinues.Ifyouanswer No (thedefault answer), theShellreturnstofileselectionwithallprevious selections intact.
The functionchanges thename ofoneor morefiles.Use theCRSRkeysandSPACE BARtoselect afiletorename. The message ‘ENTERNEWNAME:’isdisplayed alongwith theoriginalfilename. Youmustnowtype inthenewname or pressF5toun-select thatfileand continue.
Each newfilename ischecked toassure thatitisunique. Ifitisn’t,themessage ‘ERROR: FILE NAME NOT UNIQUE—RETRY’isdisplayed andthefunction returnstothe ‘ENTER NEWNAME:’message.
Press the F5keytorestart fileselection withallprevious selectionscancelled.
Press the STOP key tocancel thefunction andreturn totheprimary menu.
REORDER DIRECTORY
This functionchangestheorder inwhichthefilenamesappear inadiskettedirectory. After youselect thisfunction, youareaskedifyou‘WANT TOALPHABETIZEDIRECTORY: NY’.The defaut answer isNo.Ifyouanswer Yes,the filenamesare automatically reordered alphabetically.
Whetheryouanswered YesorNototheALPHABETIZE DIRECTORY question, youcan manually reorder thedirectory. Select afilewiththeCRSRkeysandSPACEBAR. Then use the CRSRkeysto‘drag’thefilenamethroughthefilelisttoitsnewlocation. Pressthe SPACE BARtodeposit thefilename.
Press the STOP keytocancelthefunction andreturntotheprimarymenu.
37
Page 46
38
Page 47
PARTTWO:
ADVANCED OPERATION ANDPROGRAMMING
CHAPTER5
SEQUENTIAL DATA FILES
THECONCEPTOF FILES
Afileon adiskette isjustlikeafilecabinet inyour office—anorganizedplace toputthings. Nearlyeverything you put onadiskette goesinonekind offileor another. Sofar allyou’veusedare programfiles,but thereareothers.Inthischapter you’lllearnaboutsequentialdata files.
The primarypurpose ofadata fileistostorethecontents ofprogramvariables, sotheywon’tbelostwhen the programends. Asequentialdata fileisone inwhichthecontentsofthevariablesarestored“insequence,’’one right afteranother. Youmayalready be familiar with sequential filesfromusingaDATASSETTE™,becausesequentialfileson diskette arejust likethe datafilesusedoncassettes.Whether oncassetteor diskette, sequential filesmust be read frombeginning toend.
When sequential filesare created, information(data) istransferred byte-by-byte,through abuffer, ontothe magnetic media. Onceinthediskdrive, programfiles,sequentialdata files, and user filesallworksequentially. Eventhedirectoryactslikeasequentialfile.
Touse sequential filesproperly, wewilllearnsome moreBASICwordsinthenextfewpages.Thenwe’llputthemtogether inasimple but usefulprogram.
NOTE: Besides sequential data files,twoother filetypesarerecordedsequentiallyonadiskette.Theyare program files, anduserfiles.Whenyousaveaprogramonadiskette, itissaved inorder from beginningtoend, justfiketheinformationinasequentialdatafile.The maindifference isinthecommands youusetoaccessit.User filescan beeven more similar tosequentialdatafiles.Userfilesarealmost never used, butlike programfiles,theycould betreatedasthough theyweresequentialdata filesandsome canbeaccessed withthesamecommands.
For the advanced user, thesimilarityofthe variousfiletypesoffersthepossibilityofreading aprogramfileintothecomputer abyte (character) atatimeandrewriting ittothediskette inamodifiedform.
OPENINGAFILE
Oneofthe most powerful toolsinCommodore BASICistheOPENstatement.Withit, youmaysend data almost anywhere, muchlikeatelephone switchboard.Asyoumightexpect,acommand that candothismuchisfairlycomplex.Youhave alreadyusedOPENstatementsregularly insome ofyourdiskettecommands.
Beforeyoustudythe format oftheOPENstatement, let’sreviewsomeofthepossibledevices inaCommodore computer system:
“file#”isaninteger (whole number) between 1and255. Donotopenadiskfile
with afilenumber greater than127itwillcause severe problems.After thefileisopen, allotherfilecommandswillrefer toitbythenumbergivenhere.Onlyone filecanuseanygiven filenumber atatime.
“device#”isthe number, or primaryaddress, ofthedevice tobeused. This
number isaninteger intherange 8-11, andisnormally8onthe1571.
“channel#”isasecondaryaddress, giving further instructionstotheselected
device about howfurther commands are tobeobeyed. Indiskfiles,the channelnumberselects aparticular channel alongwhichcommunicationsfor thisfilecantakeplace. Thepossible range ofdiskchannel numbers is0-15, but0isreservedfor programloads,1for programsaves, and15for thedisk commandchannel.Alsobesurethat notwodiskfileshave the same channelnumber unlessthey willnever beopenatthesametime.(Onewaytodothisistomakethechannel number for eachfilethesameasitsfilenumber.)
“drive#”isthe drive number, always0 onthe1571.Donotomitit, or youwill
onlybeable touse two channelsatthesame time insteadofthenormalmaximumofthree.Ifanypre-existing fileofthe samename istobereplaced, precede thedrive numberwiththe “at”sign (@) torequest OPEN-WITH-REPLACE.
Youcan omit the drivenumber onanOPENcommandtoreadafile.Doing soallowsthose with dualdrivestosearch bothdiskettes forthefile.
42
Page 51
ADDINGTOASEQUENTIALFILE
The APPEND command allowsyoutoreopenanexisting sequentialfileandaddmore information totheendofit.Inplaceofthe“type”and“direction”parametersinyour OPENstatement, substitute “,A”for Append.Thiswillreopenyour file,andposition the disk head atthe endoftheexistingdatainyour file,readytoaddtoit.
For instance, acomma betweenvariablesinaPRINT statementactsasaseparator inscreen displays, makingeachsuccessive itemappear inthenextpreset displayfield(typically atthe nextcolumn whosenumber isevenly divisible by10).Ifthesamecomma isincludedbetween variables going toadiskfile, itwillagainactasaseparator, againinserting extra spacesintothedata. Thistime, however, itisinappropriate,asthe extraspaces are wasted on the diskette, andmaycreate moreproblems whenreadingthe file
back intothecomputer. Therefore, follow thefollowing format preciselywhensending
data toadisk file.
FORMAT FORTHE PRINT#COMMAND:
PRINT#file#,datalist
where“file#”isthe same filenumber given inthedesiredtilescuiient OPENstatement. During anygivenaccessofaparticular file,thefilenumbermustremainconstant because itservesasashorthand wayofrelatingallother file-handlingcommands back tothe correct OPENstatement. Givenafilenumber, thecomputercanlookupeverything else about afilethatmatters.
The “data list”isthesame asfor aPRINT statement-alistofconstants, variablesand/orexpressions, including numbers, stringsor both. However, it’sbetter ifeachPRINT#statement todisk includeonlyone data item. Ifyouwishtoinclude moreitems, theyshould beseparated byacarriage returncharacter, notacomma. Semicolonsarepermitted, butnot recorded inthefile, anddo notresult inanyaddedspacesinthe file.Use them toseparateitemsinthelistthatmight otherwise be confused, suchasastringvariable immediately following anumericvariable.
NOTE: Donot leaveaspace between PRINT and#,anddonot abbreviatethecommand as?#.The correct abbreviationforPRINT#ispR.
EXAMPLES:
To record afewgrades for John PaulJones, using asequentialdiskfile#1previously
opened for writing, use:
200FORCLASS=1TOCOURSES210 PRINT#1,GRADE$(CLASS) '220 GOSUB59990:REMCHECK FORDISKERRORS320 NEXT CLASS
assuming your program includesanerror check subroutine likethe one inthelast chapter.
To get those same variables onto sequential disk filenumber5insteadofthe screen,thebest approach would betouse three separate PRINT#statements, asfollows:
CHR$(13) isthe carriage return character, andhasthesameeffect asputting theprint items inseparate lines.Ifyoudothisoften, some space andtime maybe savedbypreviously defining a variable asequaltoCHR$(13):
10CR$ =CHR$( 13)
400 PRINT#5,NAMES;CR$;STREET$;CR$;CITY$
The basic ideaisthataproper sequentialdisk-filewrite, if redirectedtothe screen,willdisplay only one data itemper line,witheachsucceedingitemonthenext line.
CLOSINGAFILE
After youfinishusing adata file,itisextremely importantthat youCLOSE it.During the processofwriting afile,data isaccumulated inamemorybuffer, andonlywrittenouttothe diskette whenthe buffer fills.
Working thisway, there isalmost alwaysasmall amountofdatainthe buffer thathasnotbeen written todiskette yet, andwhich wouldsimply belost ifthecomputer systemwereturned off.Similarly, there are diskette housekeeping matters, suchasupdatingthe BAM(BlockAvailabilityMap) ofsectorsusedbythe current file,whicharenotperformed during the ordinary course ofwriting afile.Thisisthe reason for having aCLOSE statement. When youare donewithafile, the CLOSEstatementwillwritetherestofthe data buffer out todiskette, updatethe BAM, and completethe file’sentry inthedirectory. Always close adata filewhenyouare done usingit.Failuretodosomaycause lossofthe entire file.
However, donot closethe disk command channel until allother fileshavebeenclosed. The command channel shouldbe thefirstfileopened, and thelastfileclosedinanyprogram.
FORMATFORTHE CLOSE STATEMENT
BASIC7.0: DCLOSE#file#[,Udevice#]
BASIC2.0:CLOSE file#
where“file#”isthe same filenumber given inthedesiredfile’scurrent OPENstatement.
45
Page 54
EXAMPLES:
Toclosethe data file#5used asanexample ontheprevious page, use:
BASIC7.0: DCLOSE#5
BASIC2.0: CLOSE 5
InBASIC7.0,when the DCLOSE statementisusedalone (no#or file#parameters), itclosesalldiskfilesatonce. Withabitofplanning, the samecanbedone via aprogramloop. Since thereisnoharm inclosing afilethatwasn’topen, close everyfileyoueventhink might beopenbefore endingaprogram. Ifyoualwaysgaveyour filesnumbersbetween 1and 5, youcould close themallwith
9950FOR1=1TO 5
9960 CLOSE I
9970 GOSUB59990:REMCHECK FORDISK ERRORS
9980 NEXT I
assuming your program includesanerror check subroutine like the one inthelastchapter.
READINGFILEDATA: USINGINPUT#
Once informationhasbeen writtenproperlytoadiskette file,itmaybereadbackintothe computer withanINPUT#statement. Justasthe PRINT#statementismuchlikethePRINT statement, INPUT#isnearlyidenticaltoINPUT, except that the listofitemsfollowing the command word comes from aparticular fileinsteadofthekeyboard. Bothstatementsaresubject tothe same limitations—halting inputafter acomma or colon, notacceptingdata itemstoolarge tofitinBASIC’sInput buffer, andnotacceptingnonnumericdata intoanumericvariable.
FORMATFORTHE INPUT#STATEMENT
INPUT#file#,variable list
where“file#”isthe same filenumber giveninthedesiredfile’scurrentOPENstatement, and “variable list”isone or morevalidBASICvariable names.Ifmore than
one data element istobe input byaparticular INPUT#statement, eachvariablename
must beseparated fromothers by acomma.
EXAMPLES:
Toread back inthe grades writtenwiththe PRINT#example, use:
Toreadback intheaddress data writtenbyanother PRINT#example, itissafest to
use:
800INPUT#5,NAMES
810GOSUB59990:REMCHECK FORDISK ERRORS
820INPUT#5,STREETS
830GOSUB59990:REMCHECK FORDISKERRORS
840INPUT#5,CITY$
850GOSUB59990:REMCHECK FORDISKERRORS
butmany programs cheat onsafetyabitanduse
800INPUT#5,NAMES,STREETS,CITYS
810GOSUB59990:REMCHECK FORDISKERRORS
Thisisdoneprimarilywhentopspeed intheprogramisessential, andthere islittleriskof reading improper data from the file.
MOREABOUTINPUT#(ADVANCEDUSERS)
TroublesomeCharacters
After youbegin using data filesregularly, youmayencounter twoBASICerror messages. They are“STRING TOO LONGERROR”and“FILEDATAERROR”.Botharelikelytohaltyour program atanINPUT#statement, but mayalsohavebeencausedbyerrors inaPRINT#statement whenthefilewaswritten.
“STRINGTOO LONG”ERRORS
ABASICstringmaybe upto255characters long, althoughthelongest stringyoucanenter via asingle Inputstatement isjust under twolinesoftext. Thislowerlimitationisdue tothe sizeofthe input buffer inCommodore’sserialbuscomputers.The samelimitappliestoINPUT#statements. Ifasingle data element (stringor number) being readfromadiskfileintoanINPUT#statement contains morethan88(BASIC2)and160(BASIC7)characters, BASICwillhalt witha“STRINGTOOLONGERROR.”
“FILE DATA”ERRORS
The other error message“FILEDATAERROR”iscaused byattemptingtoreadanon-numericcharacter intoanumeric variable. Toacomputer, anumberisthecharacters 0through 9, the“+”and “—”signs,thedecimalpoint (.), theSPACE character, andtheletter “E”used inscientific notation. Ifanyother character appearsinanINPUT#toanumericvariable, “FILEDATA ERROR”willbe displayed andtheprogramwillhalt.The usualcausesofthiserror are amismatchbetweentheorder inwhichvariablesarewrittentoandreadfromafile,amissing carriage return within aPRINT#statement thatwritesmore thanone data item, or adata itemthatincludeseither acomma or acolon
without apreceding quotation mark. Onceafiledataerror hasoccurred, youshould
number with the BASICVAL() statement after removing non-numeric characters withthestringfunctionsdescribed inyour computer user’smanual.
47
Page 56
COMMAS(,) AND COLONS(:)
Assuggested before, commas andcolonscancause trouble inafile,because theydelimit(end) the data element inwhichtheyappear andcause anyremaining characters inthedata element tobe read intothenext INPUT#variable. They have the sameeffect inanINPUT statement, causingthecommon “EXTRA IGNORED”error message. However, sometimes youreallyneed acomma or colonwithinadata element, suchasaname writtenas“Last, First.”The cure istoprecede such data elements withaquotationmark. After aquotation mark, ineither anINPUT or INPUT#statement, allother characters except acarriagereturn or another quotation mark areaccepted aspart ofthe currentdata element.
EXAMPLES:
To force aquotation markintoadata element goingtoafile,appendaCHR$(34) to
thestartofthe dataelement. For example:
PRINT#2,CHR$(34)+“DOE, JOHN”
or
PRINT#2,CHR$(34);“DOE, JOHN”
Ifyoudo thisoften, some space andtime maybesavedbypreviouslydefiningavariableasequaltoCHR$(34) aswedidearlier withCHR$(13):
20QT$ =CHR$(34)
400 PRINT#5,QT$+NAMES
Ineachcase, theaddedquotation mark willbe strippedfromthe databytheInput or INPUT#statement, butthe comma or colon willremainpartofthedata.
each. Incontrast, when anumericvariable or anytype iswrittentoafile,thespaceit
occupies depends entirelyonitslength, notitstype.Thisisbecausenumericdata iswrittentoafileinthe formofastring, asif theSTR$()functionhadbeenperformedonit.The firstcharacter willbeablank space if thenumber ispositive, andaminussign(-)if the number isnegative. Thencomes thenumber, digit-by-digit. The lastcharacter isacursorrightcharacter.
This format allowsthediskdatatobereadbackintoastringor numericvariablelater. Itis, however, wastefulofdisk space, anditcanbedifficulttoanticipatethespacerequired bynumbers ofunknownlength. Forthisreason,someprograms convert all
48
Page 57
numeric variablesintostringsbefore writing themtodiskette, andusestringfunctionstoremove anyunneeded characters inadvance.Doing sostillallowsthose dataelementstoberead back intoanumeric variable byINPUT#later, althoughfiledata errorsmaybeavoided byreadingalldata inasstrings, andconverting tonumbers usingthe VAL()function after the information isinside thecomputer.
For example, “N$=RIGHT$(STR$(N),LEN(STR$(N))-1)”willconvert apositive number Nintoa stringN$without the usualleading space for itsnumericsign. Then instead ofwriting PRINT#5,N,youwoulduse PRINT#5,N$.
READING FILEDATA: USINGGET#
The GET#statement retrieves data fromthe diskdrive, one character at atime.Likethe similar keyboard GET statement inBASIC, itonlyaccepts asinglecharacter intoaspecifiedvariable. However, unlike theGETstatement, itdoesn’tjustfallthrough tothenext statement ifthereisno data tobegotten. The primary use ofGET#istoretrieve fromdiskette any data thatcannotbe readintoanINPUT#statement, either because itistoo longtofitinthe inputbuffer or because itincludestroublesome characters.
FORMAT FORTHE GET#STATEMENT:
GET#file#,variablelist
where “file#”isthe same filenumber giveninthedesiredfile’scurrentOPEN
statement, and“variable list”isoneor morevalidBASICvariablenames. Ifmorethanonedata element istobeinput byaparticular GET#statement, eachvariablenamemust be separated from othersbyacomma.
Inpractice, youwillalmost never seeaGET or GET#statement containing more
thanonevariable name. Ifmorethanone character isneeded, aloopisusedrather than
Data inaGET#statement comes inbyte-by-byte, includingsuchnormallyinvisiblecharacters astheCarriage Return, andthevariouscursor controls.Allbut one willbe read properly. The exception isCHR$(0), the ASCII Nullcharacter. Itisdifferentfroman
To read afilethat maycontainaCHR$(0), suchasamachine language program
file,you could correct anyCHR$(0) byteswith
1100GET#3,G$:IFG$=””THENG$=CHR$(0)
Ifanoverlong stringhasmanagedtobe recorded inafile,itmaybereadbacksafely
intothecomputer with GET#,using aloopsuchasthis
49
Page 58
3300 B$=“”
3310 GET#1,A$
3320 IFA$OCHR$(13)THEN B$=B$+A$:GOTO 3310
The limitfor such atechnique is255characters.ItwillignoreCHR$(0), but that maybeanadvantage inbuilding atext string.IfCHR$(0)isrequired inthefile,thenuse thefollowing alternate line:
CopyingSTintoSUisoften anunnecessaryprecaution, but mustbedone if anyother file-handling statement appears betweentheone whichreadfromthe fileandtheone thatloops back toread again. For example, itwouldberequired ifline520waschanged to
Sequentialfilesare veryuseful whenyou’rejust working withacontinuous streamof
data —i.e.,information that canberead orwritten allatonce. However, sequentialfiles
are notusefulinsome situations. For example, afterwriting a large listofmaillabels, youwouldn’t want tohave torereadtheentire list eachtime youneedaperson’srecord. Instead, youneed some kindofrandom access, awaytoget toaparticularlabelinyour filewithout havingtoreadthroughallthose preceding it.
Actually, two different types ofrandomaccessfilesmaybeusedonCommodoredisk drives: relative filesandrandomfiles.Relative filesare muchmoreconvenientfor most data handling operations, buttrue randomaccessfilecommands are alsoavailable toadvanced users, and willbediscussedinthenext chapter.
FILES, RECORDS, AND FIELDS
Whenlearning about sequential files, youdidnotworryabout the organization ofdata withinafile,solong asthevariablesusedtowritethefilematched upproperlywiththose which readitback intothe computer. But inorder forrelative accesstowork,youneed amorestructured and predictableenvironment for our data.
The structure youwilluseissimilar tothatusedinthetraditional filingcabinet.Inatraditionaloffice, allcustomer records might bekept inasinglefilecabinet.Within thisfile, eachcustomerhasapersonalrecordinafilefolder withtheir name onit, that contains everything the officeknowsabout thatperson.Likewise, withineachfilefolder, theremaybe many small slipsofpaper, eachcontaining one bitofinformationabout that customer, such asahome phone number or the date ofthemost recentpurchase.
Inacomputerized office,thefilecabinet isgone, but theconcept ofafilecontainingallthe information about agroupor topicremains.The filefoldersaregone too, but thenotionofsubdividing the fileintoindividualrecords remains.The slipsofpaper withinthe personal recordsaregonetoo, replaced bysubdivisions withintherecords, calledfields. Eachfieldislarge enough toholdonepiece ofinformationabout one recordinthefile.Thus, within eachfilethere aremanyrecords, andwithineachrecord there aretypically manyfields.
Arelative filetakes care oforganizing therecordsforyou, numbering themfrom1tothe highest record number, byones, butthefieldsareuptoyoutoorganize. Eachrecord willbe ofthesame size, but the 1571won’tinsist thattheyallbedividedthesameway. Onthe other hand, they normally willbe subdividedthesameway, andifitcanbeknowninadvance exactly whereeachfieldstartswithin eachrecord,there areevenfast waystoaccessadesired fieldwithinarecordwithout reading throughtheother fields. Asallofthisimplies, access speedisaprimaryreason for puttinginformationintoarelative disk
53
Page 62
file.Some well-writtenrelative fileprograms areabletofindandreadthe record ofone
desired person outofathousand inunder 15seconds, afeatnosequentialfileprogram
could match.
FILELIMITS
With relative files, youdon’thave toworryaboutexactlywhere onthediskette’ssurface agiven record willbestored, or whetheritwillfitproperlywithinthecurrentdisksector, or need to beextended onto thenext available sector.DOStakescareofallthat for
The onlylimitthat will concern youisthateachrecordmust bethesamesize,andtherecord length youchoose mustbe between2and254characters.Naturallytheentire filealso hastofitonyour diskette too, whichmeansthatthemorerecordsyouneed, theshorter each record must be.
CREATING ARELATIVE FILE
When arelative fileistobe usedfor thefirsttime, itsOpenstatement willcreatethe
BASIC 2.0: OPEN file#,device #,channel#,“drive #:filename, L,”+CHR$
(record length)
where “file#”isthe filenumber, normallyaninteger between 1and127;“device #”isthe device number tobe used, normally 8onthe 1571;“channel #”selectsaparticular channel alongwhichcommunications for thisfilecantake place, normallybetween 2and
14;“drive#”isthe drive number, always0onthe1571;and“filename”isthe name of the file, witha maximum lengthof16characters. Patternmatchingcharacters areallowedinthe namewhenaccessing anexisting file, but not whencreatinganewone. The recordlength isthe sizeofeachrecordwithinthefileinbytesused, including carriage returns, quotation marks andother special characters.
54
Page 63
NOTES:
1.Donot precede the filename (inBASIC7.0)or the drive number(in
BASIC2.0)withthe “at”sign(@); there isnoreason toreplace arelative file.
2.L record length (inBASIC7.0)or, L+CHR$(recordlength) (inBASIC
2.0)isonlyrequired whenarelative fileisfirstcreated, thoughitmayusedlater, solongastherecord length isthe same aswhenthefilewasfirstcreated. Sincerelative filesmaybe readfromor written toalternatelyandwithequalease, there isnoneedtospecifyReador Write mode whenopening arelative file.
3.“file#”,“device #”and“channel #”mustbevalid numericconstants,variablesorexpressions. The rest ofthecommand mustbe avalidstringliteral, variable or expression. InBASIC7.0DOPEN, whenever avariable or expression isusedasafilename itmustbe surroundedbyparentheses.
4. Only 1relative filecanbe openatatime onthe1571,althoughasequentialfileand the command channelmayalsobe openatthesame time.However, if youhave asequential and relative fileopenatthe sametime, youcan’trequest adirectory.
Toreopen anunknown relative fileoftheuser’schoice that hasalreadybeencreated,
use:
BASIC7.0:200INPUT“WHICH FILE”;FI$
210 DOPEN#5,(FI$),D0,U8
BASIC2.0: 200INPUT“WHICHFILE”;FI$
210 OPEN5,8,5,FI$
USINGRELATIVEFILES: RECORD#COMMAND
When arelative fileisopened for the firsttime, itisnotquite readyfor use. Bothtosavetime whenusing the filelater, andtoassurethat thefilewillworkreliably, itisnecessary tocreateseveral recordsbefore closingthefilefor thefirsttime.Ataminimum, enoughrecordstofillmore thantwodisksectors(512bytes) shouldbewritten. Inpractice, most programsgoaheadandcreate asmanyrecords asthe programiseventually expected touse.That approach hasthe additional benefitofavoiding suchproblems asrunning outofroomon the diskette before the entirefileiscompleted.
55
Page 64
Ifyousimply beginwriting data toajust-openedrelative file,itwillactmuchlikeasequentialfile,puttingthe data elements writtenbythe firstPRINT#statementinRecord#1,those writtenby the second PRINT#statementinrecord #2andsoon. Thismeanseachrecord must be writtenbyasingle PRINT#statement, usingembedded carriagereturnswithinthe data toseparate fieldsthatwillbe readinvia one or moreINPUT#statementslater. However, itisfar better toexplicitlyspecifywhichrecordnumberisdesired via aRECORD#command tothe disk. Thisallowsyoutoaccessrecords inanydesiredorder, hopping anywhereinafilewith equalease.
FORMATFORTHE RECORD#COMMAND:
BASIC7.0: RECORD #file#,recordnumber [,offset]
BASIC2.0:PRINT#15,“P”+CHR$(channel#+96)+CHR$
(<record #)+CHR$(>record#)+CHR$(offset)
where“file#’’isthefile#specifiedinthe current DOPENstatementfor the specifiedfile,“record number’’isthe desired recordnumber, “channel #’’isthechannelnumberspecifiedinthe current OPENstatement for thespecifiedfile,“Crecord#’’isthe lowbyteofthedesiredrecordnumber, expressed asatwo-byte integer,“>record#’’isthehighbyteofthe desired record number, andanoptional“offset’’value, ifpresent, isthebyte withintherecord atwhich afollowingReador Write shouldbegin.
InBASIC7.0,topositionthe record pointer for file#2torecordnumber3,type:
RECORD#2,3
56
Page 65
InBASIC2.0,topositiontherecordpointer for channel#2torecordnumber 3,type:
PRINT #15,“P”+CHR$(98)+CHR$(3)+CHR$(0)
TheCHR$(98) comes from addingthe constant (96)tothedesired channelnumber (2).(964-2=98) Although the command appears toworkeven when96isnotaddedtothechannel number, the constant isnormallyaddedtomaintain compatibility withthe wayRECORD#works inBASIC7.0.
Since3islessthan256, thehighbyte ofitsbinaryrepresentationis0,andtheentirevalue fitsintothe lowbyte. Since youwant toread or write fromthe beginning oftherecord,nooffset value isneeded.
Sincethesecalculations quickly become tedious, mostprograms arewritten todothemfor you.Here isanexample ofaprogram which inputsarecord numberandconvertsitintothe required low-byte/high-byte form:
450 INPUT “RECORD NUMBERDESIRED”;RE
460 IF RE<1ORRE>65535THEN 450
470RH=INT(RE/256)
480RL =RE-256*RH
490PRINT#15,“P”+CHR$(98) +CHR$(RL) +CHR$(RH)
AssumingRHand RLare calculated asintheprevious example, programs mayalsousevariablesfor the channel, record, andoffset required:
informationinit, and alsoautomaticallycreate anyother missing recordsbelowitin
number. When thefirstrecordbeyondthecurrentendrecordiswritten, theDOSreturns
“50,Record Not Present”error. Thisisexpectedandcorrect.
WRITING RELATIVEFILEDATA
The commands usedtoreadandwriterelativefiledata arethesamePRINT#,INPUT#,andGET#commands usedinthepreceding chapteronSequentialfiles.Eachcommand isusedasdescribedthere. However, someaspectsofrelative fileaccessdodifferfromsequential fileprogramming, andwewillcover those differences here.
DESIGNINGARELATIVERECORD
Asstatedearlier inthischapter, each relative recordhasafixedlength, including allspecialcharacters. Within thatfixedlength,therearetwopopularwaystoorganize variousindividualfieldsofinformation. Oneisfree-format,withindividualfieldsvaryinginlengthfromrecord torecord, andeachfieldseparatedfromthenextbyacarriage returncharacter (eachofwhichdoestakeupone character spaceintherecord). The otherapproach istouse fixed-lengthfields,thatmayor maynotbeseparatedbycarriage returns. Iffixedlengthfieldsarenotallseparatedbycarriagereturns,youwilleither need
With fixedlengthrecords, thefieldlengthsadduptoexactlytherecord length. Sincethetotal lengthisjustwithintheInput buffer sizelimitation, nocarriage returncharacters areneeded. Withvariable lengthrecords, youcantake advantage ofthevariabilityofactual addresslengths. While one name contains27letters,another mayhave only15,and the same variability existsinstreet andcitylengths. Althoughvariablelengthrecordslose one character per fieldforcarriagereturns, theycantakeadvantage ofthedifference between maximumfieldlengthandaveragefieldlength. Aprogramthatusesvariable record lengths must calculate thetotallengthofeachrecordasitisentered, tobesurethetotalofallfieldsdoesn’texceedthespace available.
Inthelasttwo chapters youhave learnedhowtouse sequentialandrelative filesseparately. But theyare often usedtogether, with thesequential fileusedtokeepbrief recordsofwhich name inthe relative fileisstoredineachrecord number. That waythecontents ofthesequential filecanberead intoastringarrayandsortedalphabetically. After sorting, atechnique known asabinarysearchcanbeusedtoquicklyfindanentered name inthe array, andreadinor writetheassociatedrecordinthe relative file.Advancedprograms canmaintain two or moresuchindexfiles,sortedindiffering wayssimultaneously.
writing information entirelyunderyour direction. Thisgivesthemalmost complete
flexibilityindata-handling programs, but imposestremendous responsibilitiesontheprogrammer, tobesurenothinggoesawry. Asaresult, theyarenormallyusedonlyincomplexcommercial programs abletoproperlyorganize data without helpfromthediskdrive itself.
Afarmore common useofdirect accesscommandsisinutilityprogramsusedto
viewand alter partsofthediskette thatarenotnormallyseendirectly. For instance,suchcommands canbeusedtochangethenameofadiskettewithout erasingallofits
Youcanalso use aBLOCK-WRITE towriteaname inTrack 1,Sector 1,ararely- used sector. This canbeused asawayofmarkingadiskette asbelongingtoyou. Here isaprogramtodoit, usingthealternate formoftheBLOCK-WRITEcommand:
THE ORIGINAL BLOCK-READAND BLOCK-WRITE COMMANDS(EXPERTUSERS)
Although the BLOCK-READandBLOCK-WRITEcommands arenearlyalwaysreplaced by theU1andU2commands respectively, theoriginalcommands canstillbeused, aslong asyoufullyunderstandtheir effects. Unlike U1andU2, B-RandB-Wallowyou toread or write lessthanafullsector.Inthecase ofB-R,thefirstbyteoftheselectedsector isusedtosetthe buffer pointer (seenext section), anddetermineshowmanybytesofthat sector are readintoadisk memorybuffer. Aprogrammaychecktobesureitdoesn’tattempt toread past the end ofdata actuallyloaded intothebuffer, bywatchingfor the value ofthe filestatusvariable STtochangefrom0to64.Whenthebuffer iswrittenback todiskette byB-W, the firstbyte writtenisthecurrentvalueofthebuffer pointer. Onlythatmanybytesare written intothespecifiedsector.B-RandB-Wmaythusbeusefulinworkingwith custom-designed filestructures.
After the above program isrun, thefirstfileonthatdiskette cannolonger beerased. If youlaterneedtoerase thatfile, rerunthesameprogram, butsubstitutetherevisedline
160below tounlock the fileagain:
160A=ASC(A$) AND191Turnoffbit6tounlock
71
Page 80
ALLOCATING BLOCKS
Onceyou have writtensomething inaparticularsector onadiskettewiththehelpof
direct access commands, youmaywish tomarkthatsector as“alreadyused”,tokeep other filesfrombeingwrittenthere. Blocksthusallocated willbesafeuntilthediskette isvalidated.
FORMAT FORBLOCK-ALLOCATECOMMAND:
PRINT#15,“BLOCK-ALLOC ATE”;drive#;track#;sector#
usually abbreviated as:PRINT#15,“B-A”;drive#;track#;sector#
where “drive #”isthedrive number, and“track#”and“sector #”arethetrackandsector containing theblock ofdatatobereadintothefilebuffer.
ALTERNATE FORMAT:
PRINT#15,“B-A:”;drive#;track#;sector#
EXAMPLE:
Ifyoutrytoallocate ablock thatisn’tavailable,theDOSwillsettheerror message tonumber 65,NOBLOCK, andsetthetrackandblock numbersintheerror message tothenextavailable trackandblocknumber. Therefore, before selecting ablocktowrite, trytoallocatethat block. Iftheblock isn’tavailable, readthenext available block fromtheerror channel andallocate itinstead. However, donotallocatedata blocks inthedirectory track. Ifthetrack number returned is0, thedisketteisfull.
Tofree thesector inwhichwewroteour name intheBLOCKWRITEexample, andallocated inthe firstBLOCK-ALLOCATEexample, wecould use thefollowingcommand:
PRINT#15,“B-F”;0;1;1
USINGRANDOM FILES (ADVANCED USERS)
Bycombining the commandsinthischapter, itispossible todevelop afile-handlingprogramthat usesrandomfiles. What youneedtoknownowishowtokeeptrackof whichblocks on the disksuchafilehasused. (Eventhoughyouknowasector hasnotbeen allocated by your randomfile,youmust alsobe sureitwasn’tallocatedbyanother unrelated fileon thediskette.)
The mostcommon wayofrecording whichsectorshave beenusedbyarandomfileisinasequential file.The sequential filestoresalistofrecordnumbers,withthe track,sector, andbyte location ofeachrecord. Thismeansthreechannels areneededbyarandomfile:one for the command channel, one for therandomdata, andthe lastfor thesequential data.
73
Page 82
CHAPTER 8
INTERNALDISKCOMMANDS
Expert programmers cangive commands thatdirectlyaltertheworkingsofthe 1571,much asskilledprogrammers canaltertheworkingsofBASICinside thecomputer withPeeks, Pokes and Syscalls. Itisalso possible towritemachine language programs thatloadandrun entirely withinthe 1571,either bywritingthemintodisk memoryfromthecomputer, or byloading themdirectly fromdiskette intothedesireddiskmemorybuffer. This issimilar toloadingandrunning machine language programsinyour computer.
Aswhenlearning touse Peek, Poke andSysinyour computer, extreme caution isadvised inusing thecommandsinthischapter. Theyareessentiallymachine language commands, and lackallofBASIC’Ssafeguards.Ifanythinggoeswrong,youmayhave toturn the disk driveoffand on again (afterremoving thediskette)toregaincontrol.Donotpractice thesecommandsonanyimportantdiskette. Rather, make aspare copyandworkwiththat. Knowinghowtoprograma6502 inmachine language willhelpgreatly, andyouwillalso needagood memory mapofthe1571.Abrief1571mapappearsbelow.
1571MEMORYMAP
Location
0000-00FF0100-0 IFF0200-02FF0300-07FF
1800-65C22A
1C00-65C22A8000-FFE5FFE6-FFFF
NOTE: The 1571, aswell asother Commodore peripherals, isdesignedtosupport interfacing via software command structures. The software commands providedinthe 1571allowfor a smoothandcontrollable interfacebetween the peripheral andCPU. Commodore reserves the right tochange the ROMandI/Ostructureatanytime.
Here’samoregeneral purpose program that readsoneor morelocationsanywhereindiskmemory:
110OPEN15,8,15120INPUT“#OF BYTESTOREAD (0=END)”;NL130IFNLC1THEN CLOSE 15:END140IFNL>255THEN 120150INPUT“STARTING AT ADDRESS”;AD160AH=INT(AD/256):AL =AD-AH*256 170PRINT#15,“M-R”CHR$(AL)CHR$(AH)
The MEMORY-WRITE commandistheequivalent oftheBASICPoke command, but has itseffect indiskmemoryinsteadofwithinthecomputer.M-Wallowsyoutowriteup to34bytes atatime intodisk memory. The MEMORY-EXECUTEandsomeUser commands can beusedtorunanyprograms writtenthisway.
We can use thislinetoturnoffthe‘‘bumps”whenloading DOS-protectedprograms (i.e.,programs that have beenprotectedagainst being copiedbycreating andchecking for specific diskerrors).
PRINT#15/‘M-W’’CHR$(106)CHR$(0)CHR$( 1)CHR$( 133)
The following linecan be used torecover badsectors,suchaswhenanimportant filehasbeen damaged andcannot be readnormally.
PRINT#15,”M-W’’CHR$( 106)CHR$(0)CHR$( 1)CHR$(31)
Thesetwoexamples maybe veryuseful under somecircumstances.Theyaretheequivalent ofPOKE106,133 and POKE106,31respectively, but indisk memory, notinside the computer. Asmentioned inthe previoussection’sfirstexample, location106inthe 1571disk drive signifiesthree separate activitiestothedrive, allrelated toerror recovery. Bit7(thehigh bit), ifsetmeansnobumps(don’tthump thedrive backtotrack
1).Bit6, ifset, meansnoseeks. Inthatcase, thedrive won’tattempt toreadthehalf-trackabove and below the assignedtrack toseeifitcanreadthe data thatway. The bottomsixbitsare thecount ofhow many times thedisk willtrytoreadeachsector beforeandaftertrying seeks andbumpsbeforegiving up. Since31isthelargestnumberthatcanbeexpressed insixbits, that isthe maximumnumberoftriesallowed.
From thisexample, youcanseethevalueofknowingsomethingabout Peeks, Pokes,and machine-language before usingdirect-access diskcommands, aswellastheir potential power.
MEMORY-EXECUTE
Anyroutine indiskmemory, either inRAMorROM, canbeexecutedwiththe MEMORY-EXECUTE command. It istheequivalentoftheBASICSyscalltoamachine language program or subroutine, but worksindiskmemoryinsteadofwithinthecomput-
FORMAT FORTHE MEMORY-EXECUTE COMMAND:
PRINT #15,”M-E ”CHR$(<address)CHR$( >address)
where”<address”isthe loworder part, and”>address”isthehighorder part oftheaddressindiskmemoryatwhichexecutionistobegin.
77
Page 86
ALTERNATE FORMAT:
PRINT#15/‘M-E’’CHR$( <address)CHR$( >address)
EXAMPLE:
Here isaMEMORY-EXECUTE commandthatdoesabsolutelynothing. The firstinstructionitexecutes isanRTS, whichends thecommand:
PRINT#15/‘M-E”CHR$(179)CHR$(242)
Amoreplausible use for thiscommand wouldbe toartificiallytriggeranerror message. Don’tforget tocheck theerror channel, or you’llmissthemessage:
Most User commandsareintended tobeusedasmachine language JMP or BASICSYScommands tomachine language programs thatreside insidethediskmemory. However, some ofthemhaveother usesaswell. The UserlandUser2commandsareusedtoreplace theBLOCK-READ andBLOCK-WRITEcommands, UIre-startsthe1571without changing itsvariables, UJcold-starts the1571almost asif ithadbeenturnedoff andonagain.
Thiscommand loadsauser-type fileintothedrive RAM. The firsttwo bytesofthefilemust contain thelowandhighaddresses respectively. The thirdbyteisthe amount ofcharacters tofollow.Inaddition, atrailing checksumbytemust beincluded. The loadaddress isthe starting address.
FORMAT FORTHE UTILITYLOADERCOMMAND
PRINT #‘‘&0:filename ’’
NOTE:Thefilenameparameterisvalidonlyin1571 mode.
80
Page 89
CHAPTER 9
MACHINE LANGUAGE PROGRAMS
Here isalistofhost computer disk-related Kemal ROMsubroutinesandapracticalexample oftheiruseinaprogramwhichreads asequential fileintomemoryfromdisk. Note that most require advance setup ofone or moreprocessor registers or memorylocationsand allare called withthe assembly language JSRcommand.
For amore complete description astowhateachroutine doesandhowparametersaresetfor eachroutine, seethe Programmer’sReference Guide for your specificcomputer.
;SETLOGICAL, FIRST &SECOND ADDRESSES;SETLENGTH&ADDRESSOFFILENAME;OPENLOGICALFILE;CLOSELOGICALFILE;SELECTCHANNELFORINPUT;SELECTCHANNELFOROUTPUT;CLEARALLCHANNELS&RESTORE
“U0>R”+CHR$(RETRIES)“U0>T”(IftheROMsignaturefailed,theactivityLEDblinks4times) “U0>M1”=1571MODEL“U0>M0”=1541MODE“U0>H0”=SIDEZERO“U0>H1”=SIDE ONE (1571modeonly)“U0>”+CHR$(#DEV),where#DEV=
Before using the following burst transfer routines, youmustdetermine whether or not theperipheral isafast device. The FastSerial (bytemode)protocol makesthatdetermination internally when youinclude a queryroutine (send-cmd-string;). Thisroutine addressestheperipheral asalistener andtherebydetermines itsspeed.
BURSTREAD
send-cmd-string;if device-fast then
serial-in; toggle-clock; repeat
read-error;toggle-clock;
repeat
untillast-byte; untillast-sector; set-clock-high;
else
read-1541;
wait-byte;toggle-clock; store-data;
(*determine speed*)
(*tum 6526toinput*) (♦toggle state ofclockline*) (♦repeat for allsectors*) (♦retrieve error byte*)(*noerror*)(♦repeat for allsectors*) (♦poll6526forbyte*) (♦toggle clock*)(♦save data*)(♦last byte ?*)(*any moresectors?*)(♦release clockline*)
(♦send unit read*)
89
Page 98
BURSTWRITE
send-cmd-string;ifdevice-fast then
repeat
serial-out;
repeat
send-byte;
until last-byte;serial-in; clock-low; read-err; clock-high;
The figurebelow shows thebursttransfer protocol.Itisastat-dependent protocol(simple andfast). Astheclock line istoggled, abyteof dataissent. Burstprotocolisdividedintothree parts:
1.SendCommand: sendstringusingexisting kemal routines.
2.Query:determine whether theperipheralisfast.
3.Handshake Code:follow handshake conventions.
DATA
CLK
irzn
(AcknowledgeandReadyForData)
RFD(ReadyForData)
__
i
SRQ
EXAMPLEBURST ROUTINES
*=$1800
;ROUTINE TO READ N-BLOCKSOFDATA;COMMAND CHANNEL MUST BEOPENONDRIVE;OPEN 15,8,15;BUFFER AND CMD_BUF, ANDCMD_LENGTHMUST BESETUP;PRIORTOCALLING THISCOMMAND.
serial=$0alcd2praclkoutdlicrdlsdr=$dc0c
=SddOO=$10=$dc0d
;fastserialflag
91
Page 100
stat=$fabuffer =$fb
Idaldx#8;device numberldy#15;secondaryaddress
jsr
;$fb&$fc
#15
;logicalfilenumber
setlfs;setup logicalfile
Ida
#0
;noname
jsrsetnam;setup filename
jsr
open;open logical channel
;after the command channel isopen subsequent calls shouldbe from ‘read’
readIda#$00
stastat;clear statusIdaserialand#%10111111
;clear bit 6fast serialflagstaserialldx#15jsrchkout;open channel for outputldx#0ldycmdJength;length ofthe command
senditIda
cmd_buf,x;get command
jsr
bsout
;send the commandinxdeybnesendit
jsrclrchn;sendeoibitserial;check speedofdrivebvc
error;slowserial drive
seibitdlicr;clear interrupt control regldxcmcLbuf+5;get #ofsectorsIdad2pra;readserial porteor#clkout;change stateofclock