
Once
you've
mastered
the
basic
steps
however,
you
will
needtorefertothe
rest
of
this
manual
in
order
to
make
full
use
of
the
1541
*s
features.
In
fact,
before
you
begin,
you
should
takealookatthe
following
short
sections,
which
offer
precautions
on
handling
the
equipment:
"Simple
maintenance
tips,"
"Safety
rules
for
diskette
care,"
and
"Safety
rules
for
removing
diskettes."
1.
Unpack,
hook-up,
and
turnonthe
disk
drive.
There'snoshortcut
through
this
part.
You'll
havetoread
this
sectiontofind
out
what
connectstowhat,
whentoturn
everything
on,
and
howtoempty
the
drive.
If
you
run
into
any
problemsatthis
point,
refertothe
Troubleshooting
Guide.
Gently
insertapre-programmed
diskette.
For
the
purposeofdemonstration,
use
the
Test/Demo
diskette
that
was
included
with
the
disk
drive.
If
you
run
into
any
problemsatthis
point,
refertoChapter2,"Inserting
a
Diskette."
3.
Type:
LOAD
"HOW
TO
USE",8
(forBasic2)
DLOAD
"HOW
TO
USE"(for
Basic
3.5)
Press:
RETURN
HOW
TO
USE
is
the
name
ofaparticular
program
on
the
Text/Demo
diskette.
To
loadadifferent
BASIC
program,
substitute
the
name
of
that
program
inside
the
quotation
marks.
If
you
want
to
loadaprogram
that
isn't
written
in
BASIC
language,
you
must
use
the
Basic2command
and
add
the
following
after,the
8
in
that
command:
,1
If
you
run
into
any
problems
at
this
point,
refer
to
Chapter
2,
the
section
enti
tled
"LoadingaPackaged
Program."
4.
After
you
perform
step3,the
following
will
appearonthe
screen:
SEARCHING
FOR
HOW
TO
USE
LOADING
READY
At
this
point,
type
RUN
and
press
the
RETURN
key
and
follow
the
directions
for
the
program.

EMPTY
THE
DRIVE
First,itis
very
important
tobesure
nothingisinside the
disk
drive.Ifyou
turn
the
power
off
or
oh
withadiskette
in
the
drive,
you
could
lose
its
contents
and
have
to
re-
record
it.
Since
you
wouldn't
like
havingtodo
that,
always
checktobe
sure
nothing
is
inside
the
drive
before
turningitofforon.
When
you
first
unpack
the
disk
drive,
you
will
findacardboard
shipping spacer
inside.
Following
the
instructions
below,
pullitoutasthoughitwereadiskette,
but
don't
throwitaway.
You
will
wanttoputitback
inside
the
slot
any
time
you
moveorship
the
disk
drive
later.
To
check
whether
the
driveisempty
(Fig.
1),
simply
rotate
the
leveronthe
front
of
the
disk
drive
counter-clockwise
untilitstops,
one-quarter
turnatmost.
Then
reach
inside
the
long
slot
the
lever
covers
whenitpoints
down,
and
pull
out
any
diskette
you
find
there.
CONNECTING
THE
CABLES
With
the
power
supply,
the
power
cable
plugs
into
the
backofthe
disk
driveatone
end,
and
intoagrounded
(3-prong)
outletatthe
other
end.It
will
onlygoin
one
way.
Before
you
plugitin
though,
make
sure
that
your
entire
computer
systemisturned
off.
The
disk
drive's
on/off
switchisin
the
back,onthe
right
side
(when
viewed
from
the
back).Itis
off
when
the
botton
halfispushed
inward.
Leave
your
whole
system
off
until
everything
is
connected.Wewill
tell
you
whenitis
safe
to turniton.
Fig
2.
Back
Panel
DIP
SWITCH
FOR
CHANGING
POWER
SWITCH
DEVICE
NUMBER
SERIAL
INTERFACE
POWER
ON/OFF
ON
1
SERIAL
PORT
OFF
0
POWER
CORD
SOCKET
CONNECTORS
FOR
INTERFACE
CABLES

After
plugging the
power
supply
into
the
disk
drive
andasuitable
outlet,
find
the
black
cable
that
goes
from
the
disk
drivetothe
computer.Itis
calledaserial
bus
cable
to
describe
the
way
the
computer,
and
other
accessories
communicate
with
each
other
through
its
wires.Ithasanidentical
6-pin
DIN
connectorateach
end,
which
like
the
power
connector
can
onlygoin
one
way—with
the
dimpleinthe
sideofthe
plug
facing
up.
To
pluginthe
serial
bus
cable,
find
the
dimpleonthe
sideofthe
metal
partofthe
plug
and
turn
that
side
up.
Then
pushitstraight
into
oneofthe
two
serial
bus
connectors
on
the
backofthe
disk
drive.
The
other
end
goes
into
the
similar
connectoronthe
back
of
your
computer,
marked
'*serial
bus."Ifanother
accessory,
suchasa
printer,isalready
connected
there,
unplug
the
other
device's
cable
from
the
computer,
and
attachitto
the
spare
serial
bus
connectoronthe
backofthe
1541.
Then
install
the
serial
cable
from
the
1541inthe
serial
bus
connectoronthe
backofthe
computer
(Fig
3.A.)
If
you
have
more
than
one
disk
drive,
each
added
disk
drive's
serial
bus
cable
is
plugged
into
the
second
serial
bus
connectoronthe
backofthe
previous
disk
drive,
like
a
daisy
chain
(Fig
3.B).
However,
don't
connect
the
other(s)
until
you've
learned
how
to
change
their
device
numbers,asno
two
disk
drives
can
have
the
same
device
number.
We'll
cover
waysofchanging
disk
device
numbersinAppendixA.Until
you
are
ready
to
read
that
section,
you
may
finditeasiertoleave
your
extra
drive(s)
unconnected.
TURNINGONTHE
POWER
With
everything
hooked
up,
and
the
disk
drive
empty,itis
timetoturnonthe
power.
You
can
turnonthe
powertothe
disk
and
other
devicesonthe
serial
bus
(connected
via
serial
cables)inany
order
you
like.
Justbesuretoeither
turnonthe
powertothe
computer
itself
last,orto.
use a
multiple
outlet
power
box
withamaster
switchtoturn
everything
off
andonat
once.
When
everything
is
on,
including
the
computer,
the
disk
drive
will
go
throughaself
check
forasecondorso, tobesureitis
working
correctly.
After
the
drive
is
satisfied
with
its
own
health,itwill
flash
the
green
light
once,
and
the
red
power-on
light
will
glow
continuously.Atthe
same
time,
the
computer
willbegoing
throughasimilar
self-test,
and
displaying
its
hello
messageonyourTVor
video
monitor.
Once
the
green
lightonthe
disk
drive
has
flashed
and
gone
out,itis
safetobegin
working
with
the
drive.
If
the
light
doesn'tgoout,
but
continuestoflash,
you
may
haveaproblem.
Refertothe
troubleshooting
guide
for
help.

SIMPLE
MAINTENANCE
TIPS
Your
1541
should
serve
you
well
for
yearstocome,
but
there
areafew
things
you
candoto
avoid
costly
maintenance.
1.
Keep
the
drive
well-ventilated.
Likearefrigerator,
it
needsafew
inchesofair
circulation
on
all
sidestowork
properly.
2.
Use
only
good
quality
diskettes.
Badly-made
diskettes
could
cause
increased
wear
on
the
drive's
read/write
head.Ifa
particular
diskette
is
unusually
noisyinuse,itis
probably
causing
added
wear,
and
shouldbereplaced.
3.
Avoid
using
programs
that
"thump"
the
driveasthey
load.
Many
commercial
programs,
and
diskettes
that
are
failing,
cause
the
disk
drivetomakeabumping
or
chattering
noiseasit
attemptstoreadabad
sector.
If
the
diskette
canbecopiedtoa
fresh
diskette,
dosoimmediately.
Ifitis
protected
by
its
maker
against
copying,
the
thumping
is
intentional
and
will
havetobe
endured.Beaware,
however,
that
excessive
thumping,
especially
when
the
driveishot,
caused
some
older
1541'stogo
outofalignment
and
led
to
costly
repairs.
Current
1541's
have been
redesigned
to
prevent
the
problem.
Note:
the
"Memory-Write"
exampleinChapter8temporarily
turns
off
the
bumps.
4.Itwouldbea
good
ideatohave your
1541
checked
over
about
onceayearinnormal
use.
Several
items
are
likelytoneed
attention:
the
felt
load
padonthe
read/write
head
may
be
dirty
enoughtoneed
replacement,
the
head
itself
may
needabitofcleaning
(with
91%
isopropyl
alcoholona
cotton
swab),
the
rails
along
which
the
head
moves
may
need
lubrication
(with a
special
Molybdenum
lubricant,
NOT
oil),
and
the
write
protect
sensor
may
needtobe
dustedtobe
sure
its
optical
sensor
hasaclear
view.
Since
mostofthese
chores
require
special
materialsorparts,itis
besttoleave
the
worktoan
authorized
Commodore
service
center.Ifyou
wishtodo
the
work
yourself,
ask
your
dealertoorder
the
1541
maintenance
guide
for
you
(part
number
990445),
butbeaware
that
home
repair
of
the
1541
will
void
your
warranty.
11

CHAPTER
2
DISKETTES
WHAT
ISADISKETTE?
Beforeweactually
begin
using
the
drive,
let's
takeamomenttolookatthe
Test/Demo
diskette
packed
with
the
disk
drive.Todo
this,
graspitby
the
label,
which
shouldbesticking
outofthe
paper
jacket.
Then
pullitoutofthe
jacket
which
keepsitfree
of
dust
and
other
contaminants.
(Save
the
jacket;
the
diskette
should
alwaysbekeptinits
jacket
except
when
actually
in
useinthe
disk
drive.)Itis
often
calledafloppy
diskette,
becauseitis
flexible,
even
thoughitis
not
safetobend
diskettes.
A
diskette
is
much
likeacassette
tape,
butinthe
formofa
circle
and
enclosed
within
a
protective
square
plastic
cover.Asonacassette
tape,
onlyasmall
exposed
portion
of
the
magnetic
recording
surfaceissensitive.
You
may
touch
the
restofthe
diskette
any
time
you
like,
but
avoid
touching
the
few
small
portions
that
are
not
coveredbythe
protective
cover.
Also,
never
trytoremove
this
cover.
Unlike
the
paper
jacket,
the
plastic
diskette
coverisintendedtoremainonpermanently.
Next,
notice
the
notchonone
sideofthe
diskette
(it
maybecoveredbya
piece
of
tape).
This
notchiscalled
the
write
protect
notch.
Whenitis
covered
with
the
opaque
tape
packed
with
blank
diskettes,
the
disk
drive
cannot
change
the
contentsofthat
diskette.
Never
remove
the
tapeonthe
Test/Demo
diskette.
The
labelonthe
topofthe
diskette
says
"1541
Test/Demo"onit,
and
tells
you
which
diskette
you
are
using.
Blank
diskettes
come
with
extra
labelsinaddition
to
one
appliedbythe
makerofthe
diskette.
Use
themtodescribe
your
own
diskettes.
<*Atleast
two
other
partsofthe
diskette
are
worth
mentioning:
The
hub
and
the
access
slot.
The
holeinthe
centeriscalled
the
hub.Acone-shaped
spindle
fillsitwhen
the
drive
doorisclosed,
and
its
edges
are
clamped.
This
keeps
them
from
slipping,
when
the
diskette
spinsat300
RPMinuse.
The
oval
openinginthe
diskette
opposite
the
labeliscalled
the
access
slot.Itexposes
just
enoughofthe
diskette's
surface
for
the
read/write
head
and
load
pad
inside
the drive
to
touchaone
inch
long
line
from
the centertothe
edgeofthe
diskette's
working
surface.
The
bottom
sideofthat
slotiswhere
all
the
information
is
writtenasthe
diskette
spins.
It
is
one
place
your
fingers
should
never
touch.
ACCESS
SLOT
HUB
WRITE
PROTECT
NOTCH
WHEN
COVERED,
DISKETTE
CONTENTS
CANNOT
BE
ALTERED
LABEL
Fig.4.
Position
for
Diskette
Insertion
12

SAFETY
RULES
FOR
DISKETTE
CARE
1.
Keep
the
disk
drive
and
its
diskettes
away
from
all
moisture,
dust,
smoke,
food,
and
magnets
(including
the
electromagnets
in
telephones
and
TV's).
Also
keep
them
away
from
temperatures
either
too
hotortoo cold
for
youtoworkinfor
extended
periods.
2.
When
notinthe
drive,
diskettes
shouldbestored
upright
inside
their
paper
jackets.
Do
not
allow
themtobecome
bentorfolded.
Since
the
working
partofthe
diskette
is
on
the
bottom,
never
setitdownona
table
top,orother
place
where
dustormoisture
might
affect
it,
andbeespecially
carefultokeep
your
fingers
away
from
the
openings
in
the
diskette
cover.
3.
Although
some
people
sell
kits
intendedto"double
your
diskette's
capacity"
by
cuttinganextra
write-protect
notch
intoadiskette,
itisbest
nottouse
the
other
side
of
the
diskette
on
the
1541
drive,
evenifyour
diskette
is
labeled
"double-sided."
Doing
so
will
cause
added
weartoyour
diskettes
and
drive,
and
may
cost
youanimportant
program
some
day.
4.
When
buying
diskettes,
you
may
use
any
good
quality
5lA
inch
diskette.
5.
Make
sure
the
diskette
center
holeismoreorless
centeredinits
opening
before
inserting
the
diskette
into
the
drive.
Although
the
hub
assembly
will
correctly
center
most
any
diskette,
it
wouldbevery
difficult
to
rescue
data
fromadiskette
recorded
with
its
hub
off-center.
One
waytohelp
center
diskettes
isto"tickle"
the
drive
door
shut
insteadofslammingitdown.Bygently
closing
it
part-way,
and
then
openingabit
and
then
closing
the
restofthe
way,
you
give
the
spindle
more
chancestocenter
the
diskette
properly.
Another
waytoease
diskette
centering
istobuy
diskettes
that
come
with
reinforced
hubs.
These
hard
plastic
rings
around
the
hub
opening
make
the
diskette
hub
more
rigid,
and
easiertocenter
properly.
INSERTINGADISKETTE
To
insertadisketteina
1541
(Fig.
1),
first
open
the
drive
doorbyrotating
the
door
lever
counter-clockwise
one
quarter
turn
untilitstops,
with
the
lever
level
with
the
slot
in
the
frontofthe
drive.
Grasp
the
diskettebythe
side
opposite
the
large
oval
access
slot,
and
holditwith
the
labelupand
the
write-protect
notchtothe
left.
Now
insert
the
diskettebypushing
it
straight
into
the
slot,
the
access
slot
goinginfirst
and
the
label
last.Besure
the
diskette
goesinuntilitstops
naturally,
withnopart
showing
outside
the
drive,
but
you
shouldn't
havetoforceorbenditto
getitthere.
With
the
disketteinposition,
seatitproperly
for
usebytwisting
the
door
lever
clockwise
one-quarter
turn,
vertically
over
the
slot
untilitstops.Ifit
does
not
move
easily,
stop!
You may
have
put
the
diskette
in
the
wrong
way,orincompletely.
If
that
happens,
reposition
the
diskette
until
the
door
lever
closes
easily.
13

Lastisthe
relocate
flag.Itcan
have
oneoftwo
values,0and1.If
the
relocate
flag
is
0oromitted,
all
Commodore
computers
that
use
the
1541
automatically
relocate
the
programs
they
loadtoliveinthe
partofcomputer
memory
reserved
for
BASIC
programs.
If
the
relocate
flag
valueis1,
auto-relocation
is
turned
off,
and
the
programisloaded
into
the
exact
partofmemory
from
whichitwas
originally
saved.
This
feature
allows
machine-language
and
other
special
purpose
programstocome
into
the
computer
at
the
correct
location
for
themtooperate
properly.Atthis
pointinyour
learning,
the
only
thing
you
needtoknow
about
the
relocate
flagishowtouse
it.
Simply
include
the1at
the
endofthe
LOAD
commandifa
particular
program
doesn't
run
properly
when
loaded
the
usual
way.
After
you
typeinthe
command
and
press
the
RETURN
key,
the
fallowing
will
appearonthe
screen:
SEARCHING
FOR
"HOW
TO
USE"
LOADING
READY.
When
the
word
READY
and
the
flashing
cursor
reappearonthe
screen
and
the
green
light
goes
offonthe
drive,
the
program
named
"HOW
TO
USE"onthe
Test/Demo
diskette
has
been
loaded
into
the
computer.Touse
it,
just
type
the
word
RUN
and
press
the
RETURN
key.
The
same Load
command
will
also
allow
youtoload
other
prepackaged
programs
from
the
Test/Demoorother
diskettes.
Merely
substitute
the
exact
program
name
that
you
wanttouse
between
the
quotation
marksinthe
above
example,
and
that
willbethe
program
the
computer
will
load(alistofTest/Demo
programsisshowninChapter3,in
the
section
entitled
"WhataDirectory
Shows").
Note:
here
andinthe
remainderofthe
book,wewill
assume you
areingraphic
mode,
seeing
upper
case
letters
and
graphic
characters
when
you
type.
Thisisthe
normal
condition
of
all
Commodore
computers
coveredbythis
manual
when
they
are
first
turned
on.Ifyou
now
see
lower-case
letters
when
you
type
without
using
the
SHIFT
key,
you
are
in
text
mode
instead.
Press
the
COMMODORE
key
(Q:),atthe
lower
left
cornerofyour
keyboard,
together
with a
SHIFT
keytoswitchtographic
mode.
HOW
TO
PREPAREANEW
DISKETTE:
BASIC
2
A
diskette
needsapatternofmagnetic
groovesinorder
for
the
drive's
read/write
headtofind
thingsonit.
This
patternisnotonyour
diskettes
when
you
buy
them,
but
addingittoadisketteissimple
once
you
knowtodo
it.
Hereisthe
procedure:
FORMAT
FOR
THE
DISK
NEW
COMMAND
OPEN
15,device
#,15,"Ndrive
#:diskette
name,id"
CLOSE
15
This
Open
command
willbedescribed
more
fully in
Chapters
4
and5.For
now,
just
copyitas
is,
replacing
only
the
parts
giveninlower
case.
These
include:
the
device
15

numberofthe
1541,
normally8;the
drive
number,
always0on
the
1541;
any
desired
name
for
the
diskette,
upto16
characters
in
length,
followedbya2character
diskette
ID
number.
The
Close
command
is
often
optional;
just
don't
Open
that
same
file
again
without
Closingitthe
first
time.
EXAMPLE:
OPEN
15,8,15,"N0:MY
FIRST
DISK,01":
CLOSE
15
Note:
the
chattering
or
thumping
noise
you
hear
just
after
the
disk
New
command
beginsisentirely
normal.
The
disk
mustbesureitisattrack1,whichitassures
by
stepping
outward45times
(ona35
track
diskette.)
The
noise
you
hearisthe
head
assembly
hitting
the
track1bumper
after
its
inevitable
arrival.
HOW
TO
PREPAREANEW
DISKETTE:
BASIC
3.5
A
diskette
needsapatternofmagnetic
groovesinorder
for
the
drive's
read/write
headtofind
thingsonit.
This
patternisnotonyour
diskettes
when
you
buy
them,
but
addingittoadiskette
is
simple
once
you
knowtodo
it.
Hereisthe
procedure:
FORMAT
FOR
THE
HEADER
COMMAND
HEADER'diskette
name''
,Iid,Ddrive
#
,Udevice
#
Where
"diskette
name"isany
desired
name
for
the
diskette,
upto16
characters
in
length;
"id"isa2character
disketteIDnumber;
"drive#"is
the
drive
number, 0
if
omitted
(asitmustbeon
the
1541);
and
"device#"is
the
disk's
device
number,
assumed
tobe8ifomitted.Asdescribedinthe
next
page,
"id"isoptionalif(and
only
if)
the
diskette
has
been
previously
formattedona
1541.
Also,
theIDmustbea
string
literal,
not
a
variableorexpression,
and
may
not
include
Basic
reserved
words.
Thus,
",IFI"
cannot
be
used
becauseIfisaBasic
keyword,
and
",I(A$)"isnot
allowed
becauseA$is
a
variable.
",IA$"isallowed,
but
theIDnumber
willbethe
letter
"A"
plusadollar
sign
($),
not
the
contents
of
the
variable
A$.Ifyou
needavariable
ID
number,
use
the
Basic
2
formofthe
format
command.
EXAMPLE:
HEADER
"MY
FIRST
DISK,I01,DO"
Note:
the
chattering
or
thumping
noise
you
hear
just
after
the
Header
command
beginsisentirely
normal.
The
disk
mustbesureitisattrack1,whichitassures
by
stepping
outward45times
(ona35
track
diskette).
The
noise
you
hearisthe
head
assembly
hitting
the track1bumper
after
its
inevitable
.arrival.
REUSINGANOLD
DISKETTE
After
you
have
once
formatted
a
particular
diskette,
you
can
re-format
itasthough
it
were
brand
newatany
time,
using
the
above
procedures.
However,
you
can
also
change
its
name
and
erase
its
programs
more
quickly
and
easilybyomitting
theIDnumber
in
16

CHAPTER
3
DIRECTORIES
WHAT
ISADIRECTORY?
Oneofthe
primary
advantages
of a
disk
driveisthatitcan,
with
nearly
equal
ease
and
speed,
access
any
partofa
diskette's
surface,
and
jump
quickly
from
one
spot
to
another.ADATASSETTE™,onthe
other
hand,
usually
readsacassette
file
from
the
beginningtothe
end,
without
skipping
around.Tosee
what'sona
cassette,
itisnecessary
to
lookatits
entire
length,
which
could
takeaslongasan
hour.Ona
disk
drive,byway
of
contrast,
itisa
quick
and
simple
mattertoviewalistofthe
programs
and
data
filesona
diskette.
This
listiscalled
the
directory.
VIEWING
THE
DIRECTORY:
BASIC
2
To
view
the
directory
in
Basic2,itisusually
necessary
to
load
it,
likeaprogram.
As
when
you
load
other
programs,
this
erases
anything
alreadyinBasic
memory,sobe
sure
to
save
any
work
you
don't
wanttolose
before
loading
the
directory
in
Basic2.(Chapter
4
describes
howtoSave
a program.)
For
example,toload
the
entire
directory
from
disk
device8,type:
LOAD'T',8
Then,todisplay*the
directoryonyour
screen
afteritloads
into
computer
memory,
type
LIST.
You
may
slow
the
listingbypressing
the
CONTROL
keyonthe
VIC20and
Commodore
64,
and
haltitentirelybypressing
the
STOP
key.
You
can
also
use
this
commandtolimit
the
directory
to
desired
filesbyusing
pattern-
matching
characters
described
laterinthis
chapter.
VIEWING
THE
DIRECTORY:
BASIC
3.5
To
view
the
directory
in
Basic
3.5,
simply
type
the
word
DIRECTORYona
blank
line,
and
press
the
RETURN
key.
Unlike
Basic
2's
methodofloadingadirectory,
this
does
not
erase
anything
alreadyinBasic
memory,soyou
can
safely
ask
foradirectory
at
almost
any
time,
even
from
within
another
program.
Again,
you
may
slowadirectory
listingonthe
Commodore16and
Plus/4byholding
down
the
COMMODORE
key(Ql),or
haltitentirely
by
pressing
the
STOP
key.
You
may
also
pauseitwith
CONTROL-S
(by
holding
down
the
CONTROL
key
while
pressing
the.
"S"
key),
and
resume by
pressing
any
other
key.
WHATADIRECTORY
SHOWS
Now
let's
lookatatypical
directoryonyour
1541
Test/Demo
Diskette.
18

PRINTINGADIRECTORY
To
makeapermanent
copyofa
directory,
perhapstofastentothe
diskette's
outer
(paper)
envelope,
you
will
needtosend
the
directory
toaprinter,
suchasCommodore's
MPS
801,
1520 and
1526
serial
bus
models.Todo
this,
you
may
needtorefertoyour
printer
manual,
but
briefly
the
procedure
for
listingadirectorytodevice4isasfollows:
LOAD44$0",8
OPEN
4,4:CMD
4:LIST
PRINT#4:CLOSE
4
Also
note
that
allofthe
statements
that
can be
combinedonone
line
already
have
been.
Type
theminimmediate
modetoavoid
disturbing
the
directory.
All
other
options,
suchasdiffering
device
numbers,
and
selective
directories
(see
next
section)
can
alsobespecified
as
usualinthe
Load
command.
WARNING:Besuretoinclude
the
PRINT#
command
after
every
printer
listing.
Otherwise,
the
printer
will
remainasan
unwanted
listener
on
the
serial
bus,
and
may
disrupt
other
work.
Also,donot
abbreviate
PRINT#as?#.
Although
it
will
look
proper
when
listed
out,itwill
causeaSYNTAX
ERRORinuse.
The
proper
abbreviation
for
PRINT#ispR.
READINGADIRECTORYASA
FILE
If
you
would
liketoreadadirectory
from
withinaprogram,
you
maydoso.InBasic
3.5,
simply
include
the
DIRECTORY
commandinyour
Basic
program.InBasic
2,
however,
and
optionally
in
the
others,
you
will
havetoOpen
the
directory
as
though
it
were"a
data
file
and
readitcharacter
by
character.
See
the
discussion
of
Get#inChapter
5
for
more
information.
ANOTHER
WAY
TO
BE
SELECTIVE
Before
discussing
the
pattern-matching
options
available
for
useinseveral
disk
commands,
let's
cover
one
more
thatisonly
usableina
directory.
Several
different
types
of
files
can
coexist
peacefully
on^the
same
diskette.Byaltering
our
directory
load
command,wecan
createadirectory
from
the
filesofa
single
selected
type.
Thus,
we
might
requestalistofall
sequential
data
files
(see
Chapter
5),
oneofall
the
relative
data
files
(see
Chapter
6),oroneofonly
program
files.Todo
this,
simply
addtothe
end
of
your
selective
directory
request
the
equals
sign
(=)
followedbythe
first
letterofthe
file
type
you
wantinyour
directory.
For
example,
the
Basic2command:
21

FORMAT
FOR
PATTERN
MATCHING:
EXAMPLES:
"expression*"
"C-64*"
or
"expression?expression"
"C?64
WEDGE"
or
4
'expression?expression*''''C-647WED*''
Use
anyofthe
above
patternsinanyofthe
disk
commands
whose
format
includes
a
pattern.
This
appliestoLoad,
Dload,
Directory,
Open,
Scratch,
andtothe
source
file
in
the
Copy
and
Rename
commands.
More
than
one
"?"
can
appearinthe
same
pattern.
As
you
might
expect,
their
useinpattern
matching
means
you
can't
use
the
asterisk
or
question
markina
file
name
when
savingorwritingafile
(see
next
chapter.)
23

PART
TWO:
GUIDE
TO ADVANCED
OPERATION
AND
PROGRAMMING
CHAPTER
4
COMMANDS
COMMAND
CHANNEL
Commodore
disk
drives
expecttoreceive
manyoftheir
instructions
over
what
is
knownasa
command
channel.
Althoughwewill
not
explain
the
concepts
behindituntil
Chapter6,we
will
learnitto
useitnow,soyou
can
give
your
1541
disk
the
commands
it
needstodo
some
essential
chores.
To
instruct
the
command
channel,weuseaBasic
Open
statement
to
the
disk,
with
a
secondary
addressof15.
The
usual
formofthis
statement
is:
OPEN
15,8,15
The
first15isafile
number,
and
couldbeany
number
from1to
255.Itis
used
to
match
the
secondary
address
(the
last
numberonthe
line),
whichisalso
15.
The
middle
numberisthe
primary
address,
better
knownasthe
device
number,
andisnormally
8
when
talking
with
the
1541.Asecond
disk
drive
would
usuallybe9,athird,10andsoon.
Once
the
command
channel
has
been
opened,
use
the
Basic
Print#
commandtosend
information
to
the
disk
drive,
and
Basic's
Input#
commandtoreceive
information
back
from
the
disk
drive.
These
two
commands
are
like
Basic's
Print
and
Input
statements,
except
that
they
use
the
device
number
specified
in
the
preceding
Open
statement
instead
of
defaulting
to
the
screen
and
keyboard
respectively.
In
Basic2,you'll
use
both
Print#15
and
Input#15
extensively,
to
send
housekeep
ing
commandstothe
disk
andtocheck
its
error
status.
Basic
3.5
has
built-in
commands
for
mostofthese
chores.
Even
so,itwillbegood
for
thoseofydu
with
Basic
3.5tosee
how
such
commands
are
sent.
SendingaCommand
via
the
Command
Channel
Hereisthe
waywesend
the
Initialize
commandtothe
disk
via
the
command
channel.
PRINT#15,"I0"
This
command
assumes
we
have
already
opened
the
file
15
to the
command
channel.
"IO"
canbereplaced
with
any
string
expression
thatisa
valid
disk
com
mand.
If
file
15
isn't
already
open,
we
can
combine
the
Open
and
the
Print#
in
a
single
statement:
OPEN
15,8,15,<4I0"
However,
this
only
works
for
the
first
disk
command
given.
After
that,
file15is
already
open,
and
Opening
it
again
would
causea"FILE
OPEN"
error.
Added
com
mands
are
sent
via
Print#
instead.
25

If
the
disk
copyofthe
program
differs
evenatiny
bit
from
the
copyinmemory,
"VERIFY
ERROR"
willbedisplayed,
to
tell
you
that
the
copies
differ.
Thisinitself
doesn't
mean
either
copyisbad, butifthey
were
supposedtobe
identical,
oneorthe
other
has a
problem.
Naturally,
there'snopointintryingtoverifyadisk
copyofa
program
after
the
originalisno
longerinmemory.
With
nothingtocompare
to,anapparent
error
will
always be announced,
even
though
the
disk
copyisalways
and
automatically
verified
as
it
is
writtentothe
disk.
FORMAT
FOR
THE
VERIFY
COMMAND:
VERIFY
"drive
#:pattern",device
#,
relocate
flag
where
"drive
#:"isan
optional
drive
number(0on
the
1541,)
"pattern"isany
string
expression
that
evaluates
toafile
name,
withorwithout
pattern-matching
characters,
and
"device#"is
the
disk
device
number,
normally8.If
the
relocate
flagispresent
and
equals1,the
file
willbeverified
where
originally
saved,
rather
than
relocated
into
the
Basic
text
area.
A
useful
alternate
formofthe
command
is:
VERIFY
"*",device#
It
verifies
the
last
file
used
without
havingtotype
its
nameordrive
number.
However,
it
won't
work
properly
after
save-with-replace,
because
the
last
file
used
was
the
one
deleted,
and
the
drive
will
trytocompare
the
deleted
filetothe
programinmemory.
No
harm
will
result,
but
"VERIFY
ERROR"
will
alwaysbeannounced.Touse
verify
after
@SAVE,
includeatleast
partofthe
file
name
thatistobeverified
in
the
pattern.
One
other note
about
Verify—when
you
Verifyarelocated
file,anerror
will
nearly
alwaysbeannounced,
duetochangesinthe
link
pointers
of
Basic
programs
made
during
relocation.
Itisbesttoonly
verify
files
saved
from
the
same
typeofmachine,
and
identical
memory
size.
For
example,aBasic
program
saved
fromaVIC20can't
easily
be
verified
usingaCommodore
64,
even
when
the
program
would
work
fineonboth
machines
(unless
the
programisre-saved).
This
shouldn't
matter,asthe
only
time
you'll
be
verifying
filesonmachines
other
than
the
one
which
wrote
themiswhen
you
are
comparing
two
disk
filestoseeifthey
are the
same.
Thisisdonebyloading
one
and
verifying
against
the
other,
andassuggested,
can
onlybedoneonthe
same
machine
and
memory
sizeasthe
oneonwhich
the
files
were
first
created.
ERASING
OLD
PROGRAMS:
BASIC
2
The
Scratch
command
allows
youtoerase
unwanted
files,
and
free
the
space
they
occupied
for
usebyother
files.Itcanbeusedtoerase
eitherasingle
file,orseveral
files
at
once
via
pattern-matching.
31

"pattern"
can be
any
file
nameorcombination
of
characters
and
wild
card
characters.
As
usual,
"D"
stands
for
drive
number,
which
may
onlybe0onthe
1541.Ifthe
drive
numberisomitted,0is
assumed.
Likewise,
"U"
stands
for
unit
(device)
number,
normally
8. If
"U"isomitted,8is
assumed.
Thankstothe
defaults,
the
usual
formofthe
Scratch
command
becomes:
SCRATCH
"pattern"
Asaprecaution,
you
willbeasked:
ARE
YOU
SURE?
■
before
Basic
obeysaScratch
command.Ifyou
are
sure,
Simply
pressYand
RETURN.
If
not,
press
RETURN
aloneortype
any
other
answer,
and
the
command
willbecancelled.
The
numberoffiles
that
were
scratched
willbeautomatically
displayed.
For
exam
ple,ifyour
diskette
contains
program
files
named*'TEST'','
TRAIN",*TRUCK'',
and
"TAIL",
you
may
scratch
all
four,
along
with
any
other
files
beginning
with
the
letter
"T",byusing
the
command:
SCRATCH
"T*"
andifthe
four
listed
were
the
only
files
beginning
with
"T",
you
will
see:
01,FILES
SCRATCHED,04,00
READY.
■
The
"04"
tells
you4files
were
scratched.
SCRATCH
(FOR
ADVANCED
USERS)
Scratchisa
powerful
command,
and
shouldbeused
with
caution,
tobesure
you
only
delete
the
files
you
really
want
erased.
When
usingitwithapattern,wesuggest
you
first
use
the
same
patternina
Directory
command,tobe
sure
exactly
which
files
will
be
deleted.
That
way
you'll
havenounpleasant
surprises
when
you
use
the
same
pattern
in
the
Scratch
command.
Recovering
fromaScratch
If
you
accidentally
Scratchafile
you
shouldn't
have,
thereisstillachanceofsaving
it.
Like
Basic's
New
command,
Scratch
doesn't
really
wipe
out a
file
itself;
it
merely
clears
the
pointers
toitin
the
diskette
directory.
If
you
immediately
set
the
diskette
aside
and
protect
it
withawrite-protect
notch,tobe
surenoone
adds
any
filestothe
diskette,
a
skilled
userina
nearby
Commodore
user
group
maybeabletorecover
your
file
for
you.
It
will
helpifyou
can
remember
what
kindoffileitwas
you
scratched
(program,
sequential,
etc.),
since
that
information
cannotbedirectly
recovered
from
whatisleftofthe
file.
33

EXAMPLES:
Just
before
savinganew
copyofa
"calendar"
program,
you
might
type:
PRINT#
15/
'RO:CALENDAR/B
ACKUP=CALENDAR''
Ortomoveaprogram
called
"BOOT",
currently
the
first
programona
diskette
to
someplace
elseinthe
directory,
you
might
type:
PRINT#
15,'
'R0:TEMP=BOOT"
followedbya
Copy
command
(described
later),
which
turns
"TEMP"
intoanew
copy
of
"BOOT",
and
finishing
with
a Scratch
commandtoget
ridofthe
original
copy
of
"BOOT",
since
renamedto"TEMP"bythe
command
above.
RENAMING
PROGRAMS:
BASIC
3.5
The
Rename
command
allows
youtoalter
the
nameofa
programorother
fileinthe
diskette
directory.
Since
only
the
directory
is
affected,
Rename
works
very
quickly.
FORMAT
FOR
RENAME
COMMAND:
RENAME
"old
name"TO"new
name",Ddrive
#,Udevice
#
where
"new
name"isthe
name
you
want
the
filetohave,
and
"old
name"isthe
name
it
has
now.
"new
name"
may
be any
string
expression
that
evaluates
toavalid
file
name,
upto16
characters
in
length.If"D"isleft
out,
drive0is
assumed.If"U"isabsent,
clevice
8isassumed.
One
caution—be
sure
the
file
you
are
renaming
has
been
properly
closed before
you rename
it.
EXAMPLES:
Just
before
savinganew
copyofa
"calendar"
program,
you
might
type:
RENAME
"CALENDAR"TO"CALENDAR/BACKUP"
Ortomoveaprogram
called
"BOOT",
currently
the
first
programona
diskette
to
someplace
elseinthe
directory,
you
might
type:
RENAME
"BOOT"TO"TEMP"
followedbya
Copy
command
(described
later),
which
turns
"TEMP"
intoanew
copy
of
"BOOT",
and
finishing
withaScratch
commandtoget
ridofthe
original
copy
of
"BOOT",
since
renamedto"TEMP"bythe
command
above.
35

RENAMING
AND
SCRATCHING
TROUBLESOME
FILES
(ADVANCED
USERS)
Eventually,
you
may
run
acrossafile
which
hasacrazy
filename,
suchasa
comma
by
itself
(",")orone
that
includes
a
SHIFTed
SPACE.Orperhaps
you
will find
one
that
includes
nonprinting
characters.
Anyofthese
canbetroublesome.
Comma
files,
for
instance,
areanexception
to
the
rule
thatnotwo
files
can
have
the
same
name.
Since
it
shouldn't
be
possibletomakeafile
whose
nameisonlyacomma,
the
disk
never
expects
youtodoitagain.
Files
withaSHIFT-SPACEintheir
name
can
alsobetroublesome,
because
the
disk
interprets
the
shifted
SPACEassignalling
the
endofthe
file
name,
and
prints
whatever
follows
after
the
quotation
mark
that
marks
the
end
of a
nameinthe
directory.
This
technique
can
alsobeuseful,
allowing
youtohavealong
file
name,
but
also
make
the
disk
recognize
a
small
partofitasbeing
the
sameasthe
whole
thing
without
using
pattern-matching
characters.
In
any
case,ifyou
haveatroublesome
filename,
you
can
use
the
Chr$()
function
to
specify
troublesome
characters
without
typing
them
directly.
This
may
allow
youtobuild
them
intoaRename
command.Ifthis
fails,
you
may
also
use
the
pattern-matching
characters
inaScratch
command.
This
gives
youawaytospecify
the
name
without
using
the
troublesome
characters
at
all,
but
also
means
lossofyour
file.
For
example,ifyou
have
managedtocreateafile
named
""MOVIES",
with
an
extra
quotation
markatthe
frontofthe
file
name,
you
can
renameitto
"MOVIES"
by
using
the
Chr$()
equivalent
ofaquotation
markinthe
Rename
command:
BASIC2FORMAT:
PRINT#15,"R0:MOVIES
="+
CHR$(34)+"MOVIES"
BASIC
3.5
FORMAT:
RENAME
(CHR$(34)+"MOVIES")TO"MOVIES"
The
CHR$(34)
forcesaquotation
mark
into
the
command
string
without
upsetting
Basic.
The
procedure
forafile
name
that
includesaSHIFT-SPACEissimilar,
but
uses
CHR$(160).
In
cases
where
even
this
doesn't
work,
for
exampleifyour
diskette
contains
a
comma
file,
(one
named
",")
you
can
get
ridofit
this
way:
BASIC2FORMAT:
BASIC
3.5
FORMAT:
PRINT#15,"S0:?"
SCRATCH"?"
Dependingonthe
exact
problem,
you
may
havetobe
very
creative
in
choosing
pattern-
matching
characters
that
will
affect
only
the
desired
file,
and
may
havetorename
other
files
firsttokeep
them
from
being
scratched
too.
36

COPYING
PROGRAMS:
BASIC
2
The
Copy
command
allows
youtomakeaspare
copyofany
programorfileona
diskette.
However,ona
single
drive
like
the
1541,
the
copy
mustbeon
the
same
diskette,
which
meansitmustbegivenadifferent
name
from
the
file
copied.
It's
also
used
to
concatenate
uptofour
sequential
data
files
(combining
thembylinking
onetoanother,
endtoendina
chain).
Files
are
linkedinthe
orderinwhich
they
appearinthe
command.
The
source
files
and
other
filesonthe
diskette
are
not
changed.
Files
mustbeclosed
before
they
are
copied
or
concatenated*.
FORMAT
FOR
THE
COPY
COMMAND
PRINT#15,44COPYdrive
#:new
file=drive
#:old
file"
EXAMPLES:
PRINT#
15,4
4COPY0:B
ACKUP=ORIGINAL''
or
abbreviated
as
PRINT#15,44Cdrive
#:new
file=drive
#:old
file"
PRINT#
15/
4C0:B
ACKUP=ORIGINAL''
where
4<drive#"is
the
drive
number(0on
the
1541,)
t4new
file"isthe
copy,
and
4<old
file"isthe
original.
FORMAT
FOR
THE
CONCATENATE
OPTION
PRINT#15,44Cdrive
#:new
file=drive
#:file
l,drive#:file
2,drive
#:file
3,drive
#:file4"
where
44drive#"is
the
drive
number
for
each
file.
Sinceitis
always0on
the
1541,
the
drive
numberisoften
omitted.
EXAMPLES:
After
renaming
a
file
named
4<BOOT"to44TEMP"inthe
last
section's
example,
we
can
use
the
Copy
commandtomakeaspare
copyofthe
program
elsewhereonthe
diskette,
under
the
original
name:
PRINT#
15,4
4C0:BOOT=TEMP''
After
creating
several
small
sequential
files
that
each
fit
easilyinmemory
along
with
a
programweare
using,wecan
use
the
concatenate
optiontocombine
themina
master
file,
even
if
the
result
is
too
big
to
fit
in
memory.
(Do
be
sure
it
will
fit
in
remaining
space
on
the
diskette—it
willbeas
bigasthe
sumofthe
sizesofthe
filesinit.)
PRINT#15,44C0:A-Z
=
A-G,H-M,N-Z"
37

NOTE:
Dual
drives
make
fuller
useofthis
command,
copying
programs
from
one
diskette
to
anotherina
single
disk
unit.Todo
thatonthe
1541,
refertoAppendixEto
find
the
programs
that
you
need.
COPYING
PROGRAMS:
BASIC
3.5
The
Copy
command
allows
youtomakeaspare
copyofany
programorfileona
diskette.
However,ona
single
drive
like
the
1541,
the
copy
mustbeon
the
same
diskette,
which
meansitmustbegivenadifferent
name
from
the
file
copied.
The
source
file
and
other
filesonthe
diskette
are
not
changed.
Files
niustbeclosed
before
they
are
copied.
Although
the
1541
supportsaConcatenate
option,
Basic
3.5
doesn't
haveaspecial
command
for
it.
The
Basic2syntax
from
the
previous
page
maybeused
instead.
FORMAT
FOR
THE
COPY
COMMAND
COPY
Ddrive
#,"old
file"toDdrive
#,"new
file",Udevice
#
where
"D"isthe
drive
number
(always0on
the
1541,)
"new
file"isthe
copy,
"old
file"isthe
original,
and
"U"isthe
device
number.Ifomitted,
the
drive
number
defaults
to0and
the
device
number
(unit)to8.
EXAMPLES:
After
renamingafile
named
"BOOT"to"TEMP"inthe
last
section's
example,
we
can
use
the
Copy
commandtomakeaspare
copyofthe
program
elsewhereonthe
diskette,
under
the
original
name:
COPY
"TEMP"TO"BOOT"
To
copyafileona
second
disk
drive,wewould
use:
COPY
"ORIGINAL"TO"BACKUP"
,U9
NOTE:
Dual
drives
make
fuller
useofthis
command,
copying
programs
from
one
diskette
to
anotherina
single
disk
unit.Todo
thatonthe
1541,
refertoAppendixEto
find
the
programs
that
you
need.
VALIDATING
THE
DISKETTE:
BASIC
2
The
Validate
command
recalculates
the
Block
Availability
Map
(BAM)ofthe
current
diskette,
allocating
only
those
sectors
still
being
usedbyvalid,
properly-closed
files
and
programs.
All
other
sectors
(blocks)
are
left
unallocated
and
free
for
re-use,
and
all
improperly-closed
files
are
automatically
Scratched.
However,
this
bare
description
of
its
workings
doesn't
indicate
either
the
powerorthe
dangerofthe
Validate
command.
Its
powerisin
restoring
to
good
health
many
diskettes
whose
directories
or
block
availability
maps
have
become
muddled.
Any
time
the
blocks
usedbythe
filesona
diskette
plus
the
blocks
shownasfree
don't
addupto
the
664
availableona
fresh
diskette,
Validate
is
needed,
with
one
exception
below.
Similarly,
any
timeadiskette
containsanimproperly-
38

closed
file
(splat
file),
indicated
byanasterisk
(*)
nexttoits
file
typeinthe
directory,
that
diskette
needstobe
validated.
In
fact,
but
for
the
one
exception
below,itisagood
idea
to
validate
diskettes
whenever
you
are the
least
bit
concerned
about
their
integrity.
The
exception
is
diskettes
containing
Direct
Access
files,asdescribed
in
Chapter
7.
Most
direct
access
(random)
filesdonot
allocate
their
sectorsina
way
the
Validate
command
can
recognize.
Thus,
using
Validateonsuchadiskette
may
resultinun-
allocating
all
direct
access
files,
with
lossofall
their
contents
when
other
files
are
added.
Unless
specifically
instructed
otherwise,
never
use
Validate
onadiskette
containing
direct
access
files.
(Note:
these
are
not
the
sameasthe
relative
files
described
in
Chapter
6.
Validate
maybeusedonrelative
files
without
difficulty.)
FORMAT
FOR
THE
VALIDATE
COMMAND
PRINT#15,"VALIDATE*)"
or
abbreviated
as
PRINT#15,"V0"
where
"0"isthe
drive
number
(always0on
the
1541.)Asusual,itis
assumed
file15has
been
openedtothe
command
channelonthe
1541.
EXAMPLE:
PRINT#15,"V0'
VALIDATING
THE
DISKETTE:
BASIC
3.5
The
Collect
commandinBasic
3.5isthe
same
as the
Validate
commandinBasic
2.
It
recalculates
the
Block
Availability
Map
(BAM)ofthe
current
diskette,
allocating
only
those
sectors
still
being
usedbyvalid,
properly-closed
files
and
programs.
All
other
sectors
(blocks)
are
left
unallocated
and
free
for
re-use,
and
all
improperly-closed
files
are
automatically
Scratched.
However,
this
bare
description
of
its
workings
doesn't
indicate
either
the
powerorthe
dangerofthe
Collect
command.
Its
powerisin
restoring
to
good
health
many
diskettes
whose
directories
or
block
availability
maps
have
become
muddled.
Any
time
the
blocks
usedbythe
filesona
diskette
plus
the
blocks
shownasfree
don't
add
uptothe
664
available
onafresh
diskette,
Collectisneeded
(with
one
exception
below.)
Similarly,
any
timeadiskette
containsanimproperly-closed
file
(splat
file),
indicated
by
an
asterisk
(*)
nexttoits
file
typeinthe
directory,
that
diskette
needstobe
collected. In
fact,
but
for
the
one
exception
below,itisagood
ideatocollect
diskettes
whenever
you
are
the
least
bit
concerned
about
their
integrity.
Just
note
the
numberofblocks
freeinthe
diskette's
directory
before
and
after
using
Collect,
andifthe
totals
differ,
there
was
indeed
a
problem,
and
the
diskette
should
probablybecopied
ontoafresh
diskette
filebyfile,
using
the
Copy
command
describedinthe
previous
section,
rather
than
usingabackup
commandorprogram..
The
exceptionisdiskettes
containing
Direct
Access
files,asdescribed
in
Chapter
7.
Most
direct
access
(random)
filesdonot
allocate
their
sectorsina
way
Collect
can
recognize.
Thus,
collecting
suchadiskette
may
resultinun-allocating
all
direct
access
39

files,
with
lossofall
their
contents
when
other
files
are
added.
Unless
specifically
instructed
otherwise,
never
collect
a
diskette
containing
direct
access
files.
(Note:
these
are
not
the
sameasthe
relative
files
describedinChapter6.Collect
maybeused
on
relative
files
without
difficulty.)
FORMAT
FOR
THE
COLLECT
COMMAND
COLLECT
Ddrive
#,Udevice
#
where
"D"isthe
drive
number
(always0on
the
1541,)
and
"U"
the
device
number.
As
usual,ifomitted
they
defaulttodrive0and
device8respectively.
EXAMPLE:
COLLECT
DO
INITIALIZING
One
command
that
should
not
oftenbeneededonthe
1541,
butisstillofoccasional
valueisInitialize.
On
the
1541,
and
nearly
all
other
Commodore
drives,
this
function
is
performed
automatically,
whenever
a
new
diskette
is
inserted.
(The
optical'
write-protect
switch
is
used
to
sense
whenadiskette
is
changed.
>'
The
resultofan
Initialize,
whether
forcedbya
command,ordone
automatically
by
the
disk,isa
re-reading
of
the
current
diskette's
BAM
(Block
Availability
Map)
into
a
disk
buffer.
This
information
must,ofcourse,
alwaysbecorrectinorder
for
the
disk
to
store
new
files
properly.
However,
since
the
choreishandled
automatically,
the
only
time
you'd
needtouse
the
commandisif
something
happenedtomake
the
information
in
the
drive
buffers
unreliable.
Even
so,
you
may
use
the
command
for
reassurance,
as often
as
you
like,solongasyou
close
all
your
files
except
for
the
command
channel
first.
FORMAT
FOR
THE
INITIALIZE
COMMAND
EXAMPLE:
PRINT#15,ttINITIALIZEdrive#"PRINT#
15,"INITIALIZE
0"
oritmaybeabbreviated
to
PKINT#15,''Idrive
#"
PRINT#15,t<I0"
where
the
command
channelisassumedtobe
opened by
file
15,
and
"drive#"is0on
the
1541.
40

CHAPTER
5
SEQUENTIAL
DATA
FILES
THE
CONCEPTOFFILES
A
fileona
diskette
is
just
likeafile
cabinetinyour
office—an
organized
placetoput
things.
Nearly
everything
you
putona
diskette
goesinone
kindoffileoranother.Sofar
all
we've
used
are
program
files,
but
there
are
others,aswe
have
mentioned.
In
this
chapterwewill
learn
about
sequential
data
files.
Aswejust
suggested,
the
primary
purposeofa
data
fileisto
store
the
contents
of
program
variables,
so
they
won'tbelost
when
the
program
ends.Asequential
data
file
is
oneinwhich
the
contentsofthe
variables
are
stored
"in
sequence,"
one
right
after
another,
justaseach
linkina
chain
follows
the
previous
link.
You
may
alreadybefamiliar
with
sequential
files
from
usingaDATASSETTE™,
because
sequential
filesondiskette
are
just
like
the
data
files
usedoncassettes.
Whetheroncassette
or
diskette,
sequential
files
mustberead
from
beginning
to
end,
without
skipping
aroundinthe
middle.
When
sequential
files
are created,
information
(data)istransferred
bytebybyte,
throughabuffer,
onto
the
magnetic
media.
Onceinthe
disk
drive,
program
files,
sequential
data
files,
and
user
files
all
work
sequentially.
Even
the
directory
acts
like
a
sequential
file.
To
use
sequential
files
properly,
we
will
learn
some
more
Basic
wordsinthe
next
few
pages.
Then
we'll
put
them
together
inasimple
but
useful
program.
Note:
Besides
sequential
data
files,
two
other
file
types
are
recorded
sequentially
onadiskette,
and
maybeconsidered
varying
formsofsequential
files.
They
are
program
files,
and
user
files.
When
you
saveaprogramona
diskette,
itissaved
in
order
from
beginning
to
end,
just
like
the
information
inasequential
data
file.
The
main
difference
isinthe
commands
you
usetoaccess
it.
User
files
are
even
more
similartosequential
data
files—differing,
for
most
purposes,
in
name
only.
User
files
are
almost
never
used,
but
like
program
files,
they
couldbetreatedasthough
they
were
sequential
data
files
and
are
accessed
with
the
same
commands.
For
the
advanced
user,
the
similarity
of
the
various
file
types
offers
the
possibility
of
such
advanced
tricksasreading a
program
file
into
the
computer
a
byte
(character)
atatime
and
rewriting
ittothe
diskette
inamodified
form.
The
ideaofusing
one
programtowrite
anotherispowerful,
and
availableonthe
Commodore
disk
drives.
OPENINGAFILE
Oneofthe
most
powerful
toolsinCommodore
Basicisthe
Open
statement.
With
it,
you
may
send
almost
any
data
almost
anywhere,
much
likeatelephone
switchboard
that
can
connect
any
callertoany
destination.
As
you
might
expect,acommand
that
can
do
this
muchisfairly
complex.
You
have
already
used
Open
statements
regularly
in
some
of
your
diskette
housekeeping
commands.
42

"channel#"isasecondary
address,
giving
further
instructions
to
the
selected
device
about
how
further
commands
aretobe
obeyed.Indisk
files,
the
channel
number
selects
a
particular
channel
along
which
communications
for
this
file
can
take
place.
The
possible
rangeofdisk
channel
numbersis0-15,
but0is
reserved
for
program
Loads,1for
program
Saves,
and15for the
disk
command
channel.
Also be
sure
thatnotwo
disk
files
have
the
same
channel
number
unless
they
will
neverbeopenatthe
same
time.
(One
way
todothisisto
make
the
channel
number
for
each
file
the
sameasits
file
number.)
"drive#"is
the
drive
number,
always0on
the
1541.Donot
omit
it,oryou
will
onlybeabletouse
two
channels
at
the
same
time
insteadofthe
normal
maximumofthree.
If
any
pre-existing
fileofthe
same
nameistobereplaced,
precede
the
drive
number
with
the
"at"
sign
(@)torequest
Open-with-replace.
"file
name"isthe
file
name,
maximum
length16characters.
Pattern
matching
characters
are
allowedinthe
name
when
accessing
existing
files,
but
not
when
creating
new
ones.
"file
type"isthe
file
type
desired:
S=sequential,
P=program,U=
user,
and
L=lengthofa
relative
file.
"direction"
is
the
typeofaccess
desired.
There
are
three
possibilities:
R=read,
W=write,
andM=
modify.
When
creating
a
file,
use
"W"towrite
the
datatodiskette.
When
viewingacompleted
file,
use
"R"toread
the
data
from
diskette.
Only
use
the
"M"
(modify)
optionasa
last
ditch
wayofreading
back
data
fromanimproperly-closed
(Splat)
file.
(If
you
try
this,
check
every
byteasitisreadtobe
sure
the
dataisstill
valid,
as
such
files
always
include
some
erroneous
data,
and
havenoproper
end.)
"file
type"
and
"direction"
don't
havetobe
abbreviated.
They
canbespelled
out
in
full
for
clarityinprinted
listings.
"file
#",
"device#"and
"channel#"mustbevalid
numeric
constants,
variables
or
expressions.
The
restofthe
command
mustbea
valid
string
literal,
variable
or
expression.
The
maximum
numberoffiles
that
maybeopen
simultaneously
is
10,
including
all
filestoall
devices.
The
maximum
numberofsequential
disk
files
that
canbeopenatonce
is3(or2if
you
neglecttoinclude
the
drive
numberinyour
Open
statement),
plus
the
command
channel.
EXAMPLESOFOPENING
SEQUENTIAL
FILES:
To
createasequential
fileofphone
numbers,
you
could
use:
OPEN2,8,2,"0:PHONES,SEQUENTIAL,WRITE"
or
save
yourself
some
typing
with:
OPEN
2,8,2,"0:PHONES,S,W"
On
the
off-chance
we've
already
gota"PHONES"
fileonour
diskette,
we
can
avoid
a
"FILE
EXISTS"
error
messagebydoingan©OPEN
OPEN
2,8,2,"@0:PHONES,S,W"
44

Of
course,
this
erases
all
our
old
phone
numbers,somake
sure
that
any
information
that
maybedeletedisofnoimportance.
After
writing
our
phone
file,weremove
our
diskette
and
turn
off
the
system.
Later,torecall
the
datainthe
file,wewould
reopenitwith
something
like
OPEN
8,8,8,"0:PHONES,S,R"
It
doesn't
matter
whether
the
file
and
channel
numbers
match
the
onesweused
before,
but
the
file
name
does
havetomatch.
However,itis
possible
to
useanabbreviation
form
of
the
file
name,ifthere
arenoother
files
that
would
have
the
same
abbreviation:
OPEN
10,8,6,"0:PH*,S,R"
Ifwehave
too
many
phone
numbers,
they
might
not
fitinone
file.Inthat
case,
we
might
use
several
similar
file
names,
and
letaprogram
choose
the
correct
file.
100
INPUT
"WHICH
PHONE
FILE
(1-3)";PH
110IFPHO1
AND
PHO2
AND
PH<>3
THEN
100
120
OPEN
4,8,2,"PHONE"
+
STR$(PH)+",S,R"
You
can
omit
the
drive
numberonan
Open
commandtoread a
file.
Doingsoallows
those
with
dual
drivestosearch
both
diskettes
for
the
file.
Note:
Basic2and
Basic
3.5
use
the
same
file
handling
commands
and
the
same
direct
access
commands
(chapters
7-8).
Unless
otherwise
noted,
you
may
use
the
same
commands
for
both
throughout
the
remainderofthis
book.
ADDINGTOA
SEQUENTIAL
FILE
On
Commodore's
PET
and
CBM
models,anAppend
command
allows
youtoreopen
an
existing
sequential
file
and
add
more
information
to
the
endofit.
The
same
thing
can
be
done
another
wayonthe
1541.Inplaceofthe
"type"
and
"direction"
parameters
in
your
Open
statement,
substitute
",A"
for
Append.
This
will
reopen
your
file,
and
position
the
disk
headatthe
endofthe
existing
datainyour
file,
readytoaddtoit.
FORMAT
FOR
THE
APPEND
OPTION
OPEN
file
#,device
#,channel
#,"drive
#:file
name,A"
where,
everything
isason
the
previous
page
except
for the
ending
"A"
replacing
the
"type"
and
"direction"
parameters.
45

EXAMPLE:
If
you
are
writingagrading
program,itwouldbeconvenient
to
simply
tackoneach
student's
new
gradestothe
endoftheir
existing
grade
files.Toadd
datatothe
"JOHN
PAUL
JONES"
file,wecould
type
OPEN
1,8,3,"0:JOHN
PAUL
JONES,A"
In
this
case,
DOS
will
allocate
at
least
one
more
sector
(block)tothe
file
the
first
time
you
appendtoit,
evenifyou
only
add
one
character
of
information.
You
may
also
notice
that
using
the
CollectorValidate
command
didn't
correct
the
file
size.Onthe
other
hand,
your
dataisquite
safe,
andifthe
wasted
space
becomesaproblem,
you
can
easily
-correct
it
by
copying
the
file
to
the
same
diskette
or a
different
one,
and
scratching
the
original
file.
Here'sasequenceofcommands
that
will
copy
such
filestothe
original
diskette
under
the
original
name,
for
easeofcontinued
use:
BASIC
2:
PRINT#15,"R0:TEMP
=
JOHN
PAUL
JONES"
PRINT#15,<tC0:JOHN
PAUL
JONES=TEMFf
PRINT#15,"S0:TEMP"
BASIC
3.5:
RENAME
"JOHN
PAUL
JONES"TO"TEMP"
COPY
"TEMP"TO"JOHN
PAUL
JONES"
SCRATCH
"TEMP"
If
you
are
using
Basic2,be
suretoopen
file15to
the
command
channel
beforehand
(i.e.,
with
OPEN
15,8,15)
and
closeitafterwards
(i.e.,
with
CLOSE
15).
WRITING
FILE
DATA:
USING
PRINT#
Afterasequential
file
has
been
openedtowrite
(withatype
and
direction
of
",S,W"),weuse
the
Print#
commandtosend
datatoit
for
storageondiskette.
If
you
are
familiar
with
Basic's
Print
statement,
you
will
find
Print#
works
exactly
the
same
way,
except
that
the
listofitems
following
the
command
wordissenttoa
particular
file,
insteadofautomatically
appearingonthe
screen.
Even
the
formatting
options
(punctua
tion
and
such)
workinmuch
the
same
wayasin
Print
statements.
This
means
you
have
to
be
sure
the
items
sent
make
sensetothe
particular
file
and
device
used.
For
instance,
a
comma
between
variables
inaPrint
statement
actsasa
separator
in
screen
displays,
making
each
successive
item
appearinthe
next
preset
display
field
(typically
at
the
next
column
whose
numberisevenly
divisible
by
10).Ifthe
same
comma
is
included
between
variables
goingtoa disk
file,itwill
again
actasa
separator,
again
inserting
extra
spaces
into
the
data.
This
time,
however,itis
inappropriate,
as
the
extra
spaces
are
simply
wastedonthe
diskette,
and
may
create
more
problems
when
reading
the
file
back
into
the
computer.
Therefore,
you
are
urgedtofollow
the
following
format
precisely
when
sending
datatoa
disk
file.
FORMAT
FOR
THE
PRINT#STATEMENT
PRINT#file#,data
list
46

However,ifyou
needtocombine
them,
hereisa
safe
waytodo
it:
400PRINT#5,NAME$;CHR$(13);STREET$;CHR$(13);CITY$
CHR$(13)isthe
carriage
return
character,
and
has
the
same
effectasputting
the
print
itemsinseparate
lines.Ifyoudothis
often,
some
space
and
time
maybesaved
by
previously
defining
a
variableasequaltoCHR$(13):
10CR$=CHR$(13)...
400PRINT#5,NAME$;CR$;STREET$;CR$;CITY$
The
basic
ideaisthataproper
sequential
disk
file
write,ifredirected
to
the
screen,
will
display
only
one
data
item
per
line,
with
each
succeeding
itemonthe
next
line.
CLOSINGAFILE
WHEN
YOU
ARE
DONE
USING
IT
After
you
finish
usingadata
file,itis
extremely
important
that
you
Close
it.
During
the
processofwritingafile,
dataisaccumulated
inamemory
buffer,
and
only
written
out
to
the
physical
cassette
or
diskette
when
the
buffer
fills.
Working
this
way,
thereisalmost
alwaysasmall
amountofdatainthe
buffer
that
has
not
been
writtentodisketteorcassette
yet,
and
which
would
simplybelostifthe
computer
system
were
turned
off.
Similarly,
there
are
diskette
housekeeping
matters,
such
as
updating
the
BAM
(Block
Availability
Map)ofsectors
usedbythe
current
file,
which
are
not
performed
during
the
ordinary
courseofwritingafile.
Thisisthe
reason
for
havingaClose
statement.
Whenweknow we
are
done
withafile,
the
Close
statement
will
write the
restofthe
data
buffer
outtocassetteordiskette,
update
the
BAM,
and
complete
the
file's
entryinthe
directory.
Always
Closeadata
file
when
you
are
done
using
it!
Failuretodosomay
cause
lossofthe
entire
file!
However, do
not
cloSe
the
disk
command
channel
until
all
other
files
have
been
Closed.
The
command
channel
(described
in
the
last
chapter),
when
used,
shouldbethe
first
file
Opened,
and
the
last
file
Closedinany
program.
Otherwise,
remaining
files
may
be
closed
automatically.
As
also
described
there,
this
may
be usedtoadvantageifa
program
haltsonan
error
while
disk
files
are
open.
FORMAT
FOR
THE
CLOSE
STATEMENT
CLOSE
file
#
where
"file#"is
the
same
file
number
giveninthe
desired
file's
current
Open
statement.
EXAMPLES:
To
close
the
data
file#5usedasan
exampleonthe
previous
page,wewould
use
CLOSE
5
In
Commodore's
CBM
and
PET
computers,
thereisa
Dclose
statement,
that,
when
used
alone,
closes
all
disk
filesatonce.
Withabitofplanning,
the
same
canbedone
in
Basic2and
3.5
viaaprogram
loop.
Since
thereisno
harminclosingafile
that
wasn't
48

but
many
programs
cheatonsafetyabit
ana
use
800
INPUT#5,NAME$,STREET$,CITY$
810
GOSUB
59990:REM
CHECK
FOR
DISK
ERRORS
Thisisdone
primarily
when
top
speedinthe
programisessential,
and
thereislittleorno
riskofreading
improper
data
from
the
file.
MORE
ABOUT
INPUT#
(FOR
ADVANCED
USERS)
Troublesome
Characters
After
you
begin
using
data
files
regularly,
you
may
encounter
two
Basic
error
messages
moreorless
frequently.
They
are
"STRING
TOO
LONG
ERROR"
and
"FILE
DATA
ERROR".
Both
are
likelytohalt
your
programatan
Input#
statement,
but
may
also
have
been
causedbyerrorsina
Print#
statement
when
the
file
was
written.
"STRING
TOO
LONG"
ERRORS
A
Basic
string
maybeupto255
characters
long,
although
the
longest
string
you
can
enter
viaasingle
Input
statement
is
just
under2linesoftext(4on
the
VIC
20).
This
lower
limitation
is
duetothe88character
sizeofthe
Input
bufferinCommodore's
serial
bus
computers.
The
same
limit
appliestoInput#
statements.
Ifasingle
data
element
(string
or
number)
being
read
fromadisk
file
intoanInput#
statement
contains
more
than
87
characters,
Basic
will
halt
witha"STRING
TOO
LONG
ERROR".Toprevent
this
error,besuretolimit
each
stringtounder88characters,
and
separate
all
file
data
items
with
carriage
returns
(See
the
next
section
foracure
once
the
error
has
occurred.)
"FILE
DATA"
ERRORS
The
other
error
message
"FILE
DATA
ERROR"iscausedbyattempting
to
read
a
non-numeric
character
intoanumeric
variable.
Toacomputer,
a
numberisthe
characters
0
through
9,
the"+"an3"-"signs,
the
decimal
point
(.),
the
SPACE
character,
and
the
letter
"E"
usedinscientific
notation.
If
any
other
character
appearsinan
Input#toa
numeric
variable,
"FILE
DATA
ERROR"
willbedisplayed
and
the
program
will
halt.
The
usual
causesofthis
error
areamismatch
between
the
orderinwhich
variables
are
writtentoand
read
fromafile,amissing
carriage
return
withinaPrint#
statement
that
writes
more
than
one
data
item,ora
data
item
that
includes
eitheracommaora colon
withoutapreceding
quotation
mark.
Onceafile
data
error
has
occurred,
you
should
correctitby
reading
the
data
item
intoastring
variable,
and
then
converting
it
backtoa
number
with
the
Basic
Val()
statement
after
removing
non-numeric
characters
with
the
string
functions
described
in
your
computer
users
manual.
COMMAS
(,)
AND
COLONS
(:)
As
suggested
before,
commas
and
colons
can
cause
troubleina
file,
because
they
delimit
(end)
the
data
elementinwhich
they
appear
and
cause
any
remaining
characters
in
the
data
elementtobe
read
into
the
next
Input#
variable.
(They
have
the
same
effectinan
Input
statement,
causing
the
common
"EXTRA
IGNORED"
error
message.)
However,
sometimeswereally
needacommaorcolon
withinadata
element,
suchasa
name
written
as
"Last,
First".
The
cureisto
precede
such
data
elements
withaquotation
mark.
After
a
50

quotation
mark,ineitheranInputorInput#
statement,
all
other
characters
except
a
carriage
returnoranother
quotation
mark
are
acceptedaspartofthe
current
data
element.
EXAMPLES:
To
forceaquotation
mark
intoadata
element
goingtoa
file,
appendaCHR$(34)
to
"
the
start
of
the
data
element.
For
example:
PRINT#2,CHR$(34)
-I-''STRASMA,
JIM''
or
PRINT#2,CHR$(34);4<STRASMA,
JIM"
If
youdothis
often,
some
space
and
time
maybesavedbypreviously
defining
a
variable
as
equaltoCHR$(34)aswe
did
earlier
with
CHR$(13):
20QT$=CHR$(34)
400
PRINT#5,QT$+NAMES
In
each
case,
the
added
quotation
mark
willbestripped
outofthe
databythe
Input
or
Input#
statement,
but
the
commaorcolon
will
remain
safely
partofthe
data.
NUMERIC
DATA
STORAGEONDISKETTE
Inside
the
computer,
the
space
occupiedbya
numeric
variable
depends
onlyonits
type.
Simple
numeric
variables
use7bytes
(character
locations)
of
memory.
Real
array
variables
use5bytes
per
array
element,
and
integer
array
elements
use2bytes-
each.
In
contrast,
whenanumeric
variableorany
typeiswrittentoa
file,
the
spaceitoccupies
depends
entirely
on
its
length,
not
its
type.
Numeric
dataiswrittentoa
fileinthe
formofa
string,asif
the
Str$()
function
had
been
performedonit.
The
first
character
willbea
blank
spaceifthe
numberispositive,
andaminus
sign
(-)ifthe
numberisnegative.
Then
comes
the
number,
digitbydigit.
The
last
character
isacursor
right
character.
This
format
allows
the
disk
datatobe
read
back
intoastringornumeric
variable
later.
It
is,
however,
somewhat
wasteful
of
disk
space,
and
it
can
be
difficult
to
anticipate
the
space
requiredbynumbersofunknown
length.
For
this
reason,
some
programs
convert
all
numeric
variables
into
strings
before
writing
themtodiskette,
and
use
string
functions
to
remove
any
unneeded
characters
in
advance.
Doingsostill
allows
those
data
elements
toberead
back
intoanumeric
variable
by
Input#
later,
although
file
data
errors
maybeavoidedbyreading
all
datainas
strings,
and
converting
to
numbers
after
the
information
is
inside
the
computer.
For
example,
t4N$=MID$(STR$(N),2)"
will
convertapositive
numberNinto
a
stringN$without
the
usual
leading
space
for
its
numeric
sign.
Then
insteadofwriting
PRINT#5,N,
you
would
use
PRINT#5,N$.
51

READING
FILE
DATA:
USING
GET#
The
Get#
statement
retrieves
data
from
the
disk
drive,
one
character
atatime.
Like
the
similar
keyboard
Get
statement
in
Basic,itonly
acceptsasingle
character
into
a
specified
variable.
However,
unlike
the
Get
statement,
it
doesn't
just
fall
throughtothe
next
statement
if
thereisno
datatobe
gotten.
The
primary
useofGet#isto retrieve
from
diskette
any
data
that
cannotberead
intoanInput#
statement,
either
becauseitis
too
long
to
fitinthe
input
bufferorbecauseitincludes
troublesome
characters.
FORMAT
FOR
THE
GET#
STATEMENT:
GET#file#,variable
list
where
"file#"is
the
same
file
number
giveninthe
desired
file's
current
Open
statement,
and
"variable
list"isoneormore
valid
Basic
variable
names.Ifmore
than
one
data
elementistobeinputbya
particular
Get#
statement,
each
variable
name
must
be
separated
from
othersbya
comma.
In
practice,
you
will
almost
never
seeaGetorGet#
statement
containing
more
than
one
variable
name.Ifmore
than
one
character
is
needed,
a loopisused
rather
than
additional
variables.
Alsoasin
the
Input#
statement,
itissafertouse
string
variables
when
the
filetobe
read
might
containanon-numeric
character.
Dataina
Get#
statement
comesinbytebybyte,
including
such
normally
invisible
characters
as
the
Carriage
Return,
and
the
various
cursor
controls.
All
but
one
willberead
properly.
The
exceptionisCHR$(0),
the
ASCII
Null
character.
Itisdifferent
from
an
empty
string
(oneofthe
formA$=""),
even
though
empty
strings
are
often
referred
to
as
null
strings.
Unfortunately,
inaGet#
statement,
CHR$(0)isconverted
intoanempty
string.
The
cureisto
test
foranempty
string
afteraGet#,
and
replace
any
that
are
found
with
CHR$(0)
instead.
The
first
example
below
illustrates
the
method.
EXAMPLES:
To
readafile
that
may
containaCHR$(0),
suchasa
machine
language
program
file,
we
could
correct
any
CHR$(0)
bytes
with
1100
GET#3,G$:IF
G$ =""THENG$=
CHR$(0)
Ifanoverlong
string
has
managedtobe
recordedina
file,itmaybesafely
read
back
into
the
computer
with
Get#,
usingaloop
suchasthis
3300B$=
""
3310GET#l,A$
3320IFA$<>CHR$(13)
THENB$=B$+
A$:GOTO
3310
The
limit
for
suchatechnique
is
255
characters.
It
will
ignore
CHR$(0),
but
that
may
be
an
advantageinbuilding
a
text
string.
52

Get#
maybeespecially
usefulinrecovering
damaged
files,orfiles
with
unknown
contents.
The
Basic
reserved
variableST(the
file
STatus
variable)
canbeusedtoindicate
when
allofa
properly-closed
file
has
been
read.
500
GET#2,S$
510SU=
ST:REM
REMEMBER
FILE
STATUS
520
PRINT
S$;
530IFSU=0
THEN
500:REMIFTHERE'S
MORETOBE
REAL
540IFSUO64
THEN
PRINT
"STATUS
ERROR:ST=
";SU
CopyingSTintoSUis
often
an unneccessary
precaution,
but
mustbedoneifany
other
file-handling
statement
appears
between
the
one
which
read
from
the
file
and
the
one
that
loops
backtoread
again.
For
example,itwouldberequired
if
line
520
was
changed
to
520PRINT#l,S$;
Otherwise,
the
file
status
checkedinline
530
wouldbethatofthe
write
file,
not
the
read
file.
POSSIBLE
VALUESOFTHE
FILE
STATUS
VARIABLE
t4ST",
IFST
=
0
1
2
4
8
16
32
64
128
AND
THEIR
MEANINGS
THEN
AllisOK
Receiving
device
was
not
available
(time
outontalker)
Transmitting
device
was
not
available
(time
outonlistener)
Cassette
data
file
block
was
too
short
Cassette
data
file
block
was
too
long
Unrecoverable
read
error
from
cassette,
verify
error
Cassette
checksum
error—oneormore
faulty
characters
were
read
Endoffile
reached
(EOI
detected)
Device
not
present,orendoftape
mark
foundoncassette
53

DEMONSTRATIONOFSEQUENTIAL
FILES
Use
the
following
program
for
your
Comments
have
been
addedtohelp
you
150CR$=CHR$(13)
160
OPEN
15,8,15
170
PRINT
CHR$(147):REM
CLEAR
SCREEN
190
PRINT
"**
WRITEAFILE
**"
210
PRINT
220
OPEN
2,8,2,"@0:SEQ
FILE,S,W"
230
GOSUB
500
240
PRINT'ENTER
A WORD,
THENANUMBER1*
250
PRINT"OR
4END,0'TOSTOP*'
260
PRINT
270
INPUT
A$,B
280
PRINT#2,A$;CR$;B
290
GOSUB
500
300IFA$O"END"
THEN
270
310
PRINT
320
CLOSE
2
340
PRINT
"**
READ
SAME
FILE
BACK
**"
360
PRINT
370
OPEN
2,8,2,"0:SEQ
FILE,S,R"
380
GOSUB
500
390
INPUT#2,A$,B
400RS=ST
410
GOSUB
500
420
PRINT
A$,B
430IFRS=0
THEN
390
440IFRSO64
THEN
PRINTt4STATUS=";RS
450
CLOSE
2
460
END
480
REM**ERROR
CHECK
S/R
**
500
INPUT#15,EN,EM$,ET,ES
510IFEN>0
THEN
PRINT
EN,EM$,ET,ES:STOP
520
RETURN
first
experiments
with
sequential
files.
better
understand
it.
Makeacarriage
return
variable
Open
demo
file
with
replace
Check
for
disk
errors
Acceptastring&number
from
keyboard
Write
themtothe
disk
file
Until
finished
Tidy
up
Reopen
same
file
for
reading
Read
next
string&number
from
file
Remember
file
status
Display
file
contents
until
done,
unless
there'sanerror
Then
quit
A
Basic
3.5-only
version
could
replace
line
500
with
500IFDS>0
THEN
PRINT
DS$:STOP
and
delete
line
510
54

desired
person
outofa
thousandinunder15seconds,
a
featnosequential
file
program
could
match.
FILE
LIMITS
Oneofthe
nicest
aspectsofrelative
filesisthat
all
thisisdone
for
you
without
your
havingtoworryatall
about
exactly
whereonthe
diskette's
surface
a
given
record
will
be
stored,
or
whetheritwill
fit
properly
within
the^current
disk
sector,
or
needtobe
extended
onto
the
next
available
sector.
DOS
takes
careofall
that
for
you.
All
you
needtodo
is
specify
how
long
each
record
is,inbytes,
and
how
many
records
you
will
need.
DOS
will
do
the
rest,
and
organize
thingsinsuchaway
thatitcan
quickly
find
any
recordinthe
file,
as
soonasitisgiven
its
record
number
(ordinal
position
within
the
file).
The
only
limit
that
will
concern
you,isthat
each
record
mustbethe
same
size,
and
the
record
length
you
choose
mustbebetween2and
254
characters.
Naturally
the
entire
file
also
has
to
fit
on
your
diskette
too,
which
means
that
the
more
records
you
need,
the
shorter
each
must
be.
CREATINGARELATIVE
FILE
Whenarelative
fileistobeused
for
the
first
time,
its
Open
statement
will
create
the
file;
after
that,
the
same
Open
statement
will
be usedtoreopen
the
file
for
both
reading
and
writing.
FORMAT
STATEMENTTOOPENARELATIVE
FILE:
OPEN
file#,device#,channel#,"drive#:file
name,
L,"+CHR$
(record
length)
where
"file#"is
the
file
number,
normallyaninteger
between1and
127;
"device#"is
the
device
number
to
be
used,
normally
8
on
the
1541;
"channel
#"
selects
a
particular
channel
along
which
communications
for
this
file
can
take
place,
normally
between2and
14;
"drive#"is
the
drive
number,
always0on
the
1541;
and
"file
name'*isthe
file
name,
with a
maximum
lengthof16
characters.
Pattern
matching
characters
are
allowed
in
the
name
when
accessing
an
existing
file,
but
not
when
creating
a
new
one.
The
"record
length"isthe
sizeofeach
record
within
the
fileinbytes
used,
including
carriage
returns,
quotation
marks
and
other
special
characters.
56

450
INPUT"RECORD#DESIRED";RE
46aIFRE<1ORRE>65535
THEN
450
470RH=INT(RE/256)
480RL =
RE-256*RH
490
PRINT#15,
"P"
+CHR$
(98)
+CHR$
(RL)+CHR$
(RH)
Assuming
RH
andRLare
calculated
asinthe
previous
example,
programs
may
also
use
variables
for
the
channel,
record,
and
offset
required:
570
INPUT
"CHANNEL,
RECORD,&OFFSET
DESIRED";CH,RE,OF
630
PRINT#15,"P"+CHR$(CH+96)+CHR$(RL)+CHR$(RH)+CHR$
(OF)
ANOTHER
RECORD#
COMMAND
Basic
4.0onCommodore's
PET
and
CBM
models
includes
a
Basic
Record#
command
not
foundinanyofthe
serial
bus
computers.
However,
some
available
utility
programs
for
these
models
include
it.Itserves
the
same
functionasthe
Record#
command
explained
above,
but
hasasimplified
syntax:
RECORD#file
#,record
#,offset
where
"file#"is
the
relative
file
number
being
used,
not
the
command
channel's
file,
"record#"is
the
desired
record
number,
and
"offset"isas
above.
If
you
seeaRecord#
command
writteninBasic4formina
program
you
want
to
use,
simply
convertitinto
the
usual
form
for
both
Basic2and
3.5
described
in
this
section.
COMPLETING
RELATIVE
FILE
CREATION
Now
thatwehave
learned
howtouse
both
the
Open
and
Record#
commands,weare
almost
readytoproperly
createarelative
file.
The
only
additional
factweneedtoknow
is
that
CHR$(255)isa
special
character
inarelative
file.Itis
the
character
usedbythe
DOS
to
fill
relative
recordsasthey
are
created,
beforeaprogram
fills
them
with
other
information.
Thus,ifwe
wanttowrite
the
last
recordweexpecttoneedinour
file
with
dummy
data
that will
not
interfere
with
our
later
work,
CHR$(255)isthe
obvious
choice.
Hereishowitworksinan
actual
program
which
you
may
copy
for
useinyour
own
relative
file
programs.
1020
OPEN
15,8,15
Open
command
channel
1380
INPUT"
ENTER
RELATIVE
FILE
NAME''
;FI$
Select
file
parameters
1390
INPUT"ENTER
MAX.#OF
RECORDS";NR
1400
INPUT-ENTER
RECORD
LENGTH";RL
59

WRITING
RELATIVE
FILE
DATA
The
commands
usedtoread
and
write
relative
file
data
are
the
same
Print#,
Input#,
and
Get#
commands
usedinthe
preceding
chapteronSequential
files.
Each
command
is
usedasdescribed
there.
However,
some
aspectsofrelative
file
accessdodiffer
from
sequential
file
programming,
andwewill
cover
those
differences
here.
DESIGNINGARELATIVE
RECORD
As
stated
earlierinthis
chapter,
each
relative
record
has a
fixed
length,
including
all
special
characters.
Within
that
fixed
length,
there
are
two
popular
waystoorganize
various
individual
fieldsofinformation.
Oneisfree-format,
with
individual
fields
varying
in
length
from
recordtorecord,
and
each
field
separated
from
the
nextbya
carriage
return
character
(eachofwhich
does
takeup1
character
spaceinthe
record).
The
other
approach
is
to
use
fixed-length
fields,
that
may
or
may
not
be
separated
by
carriage
returns.
If
fixed
length
fields
are
not
all
separated
by
carriage
returns,
you
will
either
needtobe
sure
a
carriage
returnisincluded
within
each88character
portionofthe record.Ifthisisnot
done,
you
will
havetouse
the
Get#
commandtoread
the
record,ata
significant
cost
in
speed.
Relative
recordsof88orfewer
characters,
or
final
portionsofrecords
that
are88or
fewer
characters
in
length,
need
not
end
inacarriage
return.
The
1541
is
smart
enough
to
recognize
the
endofa
relative
record
even
without a
finahcarriage
return.
Though
the
savingofa
single
character
isn't
much,
when
multiplied
by
the
numberofrecordsona
diskette,
the
savings
couldbesignificant.
Since
each
relative
record
mustbewrittenbya
single
Print#
statement,
the
recom
mended
approachisto
buildacopyofthe
current
recordinmemory
before
writingitto
disk.Itcanbecollected
intoasingle
string
variable
with
the
helpofBasic's
many
string-
handling
functions,
and
then
all
written
outatonce
from
that
variable.
Hereisan
example.Ifwe
are
writing
a
4-line
mail
label,
consisting
of4fields
named
"NAME",
"STREET",
"CITY&STATE",
and
"ZIP
CODE",
and
haveatotal
record
sizeof87
characters,
we
can
organizeitin
eitheroftwo
ways:
WITH
FIXED
LENGTH
FIELDS
WITH
VARIABLE
LENGTH
FIELDS
Field
Name
Length
Field
Name
Length
NAME
27
characters
NAME
31
characters
STREET
27
characters
STREET
31
characters
CITY&STATE
23
characters
CITY&STATE
26
characters
ZIP
CODE
10
characters
ZIP
CODE
11
characters
Total
length*87
characters
Potential
length
99
characters
Edited
length
87
characters
With
fixed
length
records,
the
field
lengths
addupto
exactly
the
record
length.
Since
the
total
lengthisjust
within
the
Input
buffer
size
limitation,
no
carriage
return
characters
are
needed.
With
variable
length
records,wecan
take
advantageofthe
variability
of
actual
address
lengths.
While
one
name
contains27letters,
another
may
have
only
15,
and
the
same
variability
existsinStreet
and
City
lengths.
Although
variable
length
records
lose1character
per
field
for
carriage
returns,
they
can
take
advantageofthe
difference
61

channelisopened
much
like
other
files,
except
that
the
pound
sign
(#),
optionally
followedbya
memory
buffer
number,isusedasa
file
name.
FORMAT
FOR
DIRECT
ACCESS
FILE
OPEN
STATEMENTS:
OPEN
file
#,device#,channel#,"#buffer
#"
where
"file#"is
the
file
number,
"device#"is
the
disk's
device
number,
normally
8;
"channel#"is
the
channel
number,anumber
between2and14thatisnot
usedbyother
files
open
at
the
same
time;
and
"buffer
#",
if
present,
isa0,
1,
2,
or
3,
specifying
the
memory
buffer
within
the
1541touse
for
this
file's
data.
EXAMPLES:
Ifwedon't
specify
which
disk
buffertouse,
the
1541
will
select
one:
OPEN5,8,5,"#"
Orwecan
make
the
choice
ourselves:
OPEN4,8,4,"#2"
BLOCK-READ
The
purpose ofaBlock
Readisto
load
the
contentsofa
specified
sector
into
a
file
buffer.
Although
the
Block
Read
command
(B-R)isstill
partofthe
DOS,
command
set,itis
nearly
always
replacedbytheUlcommand.
FORMAT
FOR
THE
BLOCK-READ
COMMAND:
PRINT#15,
"Ul";
channel#;drive#;track#;sector
#
where
"channel#"is
the
channel
number
specified
when
the
file
into
which
the
block
willberead
was
opened,
"drive#"is
the
drive
number,
always0on
the
1541,
and
"track#"and
"sector#"are
respectively
the
track
and
sector
numbers
containing
the
desired
blockofdatatobe
read
into
the
file
buffer.
ALTERNATE
FORMATS:
PRINT#15,"Ul:"channel
#;drive
#;track
#;sector
#
PRINT#15,"UA:"channel
#;drive
#;track
#;sector
#
PRINT#15,"Ul:channel
#,drive
#,track
#,sector
#"
66

EXAMPLES:
To
restore
track
18,
sector1of
the
directory
from
the
disk buffer
filledbythe
Block
Read
exampleonpage
82,wecan
use
PRlNT#15,"U2";5;0;18;l
We'll
returntothis
exampleonthe
next
page,
afterwelearntoalter
the
directory
in
a
useful
way.
We
can
also
useaBlock
WritetowriteanameinTrack1,Sector1,a
rarely-used
sector.
This
canbeusedasa
wayofmarkingadisketteasbelongingtoyou.
Hereisa
programtodo
it,
using
the
alternate
formofthe
Block
Write
command:
110
INPUT"YOUR
NAME"
;NA$
Enteraname
120
OPEN
15,8,15
Open
command
channel
130
OPEN
4,8,4,4t#"
Open
direct
access
channel
140
PRINT#4,NA$
Write
nametobuffer
150
PRINT#15,4tU2";4;0;l;l
Write
buffertoTrack
1,
160
CLOSE
4
Sector1of
diskette
170
CLOSE
15
Tidyupafter
180
END
THE
ORIGINAL
BLOCK-READ
AND
BLOCK-WRITE
COMMANDS
(EXPERT
USERS
ONLY)
Although
the
Block
Read
and
Block
Write
commands
are
nearly
always
replaced
by
theUlandU2commands
respectively, the
original
commands
can
stillbeused,aslong
as
you
fully
understand
their
effects.
UnlikeUland
U2,
B-R
and
B-W
allow
youtoread
or
write
less
than a
full
sector.Inthe
caseofB-R,
the
first
byteofthe
selected
sector
is
usedtoset
the
buffer
pointer
(see
next
section),
and
determines
how
many
bytesofthat
sector
are
read
intoadisk
memory
buffer.Aprogram
may
checktobe
sureitdoesn't
attempttoread
past
the
endofdata
actually
loaded
into
the
buffer,bywatching
for
the
valueofthe
file
status
variableSTto
change
from0to
64.
When
the
bufferiswritten
back
to
diskettebyB-W,
the
first
byte
writtenisthe
current
valueofthe
buffer
pointer,
and
only
that
many
bytes
are
written
into
the
specified
sector.
B-R
and
B-W
may
thus
be
usefulinworking
with
custom-designed
file
structures.
FORMAT
FOR
THE
ORIGINAL
BLOCK-READ
AND
BLOCK-WRITE
COM
MANDS:
PRINT#15,4tBLOCK-READ'';channel
#;drive
#;track
#;sector
#
abbreviated
as:
PRINT#15,"B-R";channel
#;drive
#;track
#;sector
#
and
PRINT#15,ttBLOCK-WRITE*';channel
#;drive
#;track
#;sector
#
68

abbreviated
as:
PRINT#15,"B-W";channel
#;drive
#;track
#;sector
#
where
"channel#"is
the
channel
number
specified
when
the
file
into
which
the
block
willberead
was
opened,
"drive#"is
the
drive
number
(always0on
the
1541),
and
44track#"and
"sector#"are
respectively
the
track
and
sector
numbers
containing
the
desired
blockofdatatobe
partially
read
intoorwritten
from
the
file
buffer.
IMPORTANT
NOTES:
1.Ina
true
Block-Read,
the
first
byteofthe
selected
sectorisused
to
determine
how
many
bytesofthat
sectortoread
into
the
disk
memory
buffer.
It
thus
cannotbeusedtoreadanentire
sector
into
the
buffer,asthe
first
data
byte
is
always
interpreted as
being
the
numberofcharacters
to
read,
rather
than
partofthe
data.
2.
Similarly,
inatrue
Block-Write,
when
the
bufferiswritten
backtodiskette,
the
first
byte
writtenisthe
current
valueofthe
buffer
pointer,
and
only
that
many
bytes
are
written
into
the
specified
sector.Itcannot
be usedtorewriteanentire
sector
onto
diskette
unchanged,
because
the
first
data
byteisoverwritten
by
the
buffer
pointer.
THE
BUFFER
POINTER
The
buffer
pointer pointstowhere
the
next
ReadorWrite
will
begin
withinadisk
memory
buffer.Bymoving
the
buffer
pointer,
you
can
access
individual
bytes
within
a
blockinany
order.
This
allows
youtoedit
any
portionofa
sector,
or organizeitinto
fields,
likearelative
record.
FORMAT
FOR
THE
BUFFER-POINTER
COMMAND:
PRINT#15,<4BUFFER-POINTER";channel#;byte
usually
abbreviated
as:
PRINT#15,"B-P";channel
#;byte
where
"channel#"is
the
channel
number
specified
when
the
file
reserving
the
buffer
was
opened,
and
"byte"isthe
character
number
within
the
bufferatwhichtopoint.
ALTERNATE
FORMATS:
PRINT#15,"B-P:"channel
#;byte
PRINT#15,"B-P:channel
#;byte"
EXAMPLE:
Hereisa
program
that
locks
the
first
programorfileona
1541
diskette.
It
works
by
reading
the
startofthe
directory
(Track
18,
Sector1)into
disk
memory,
setting
the
buffer
69

pointertothe
first file
type
byte
(see
AppendixCfor
detailsofdirectory
organization),
lockingitby
setting
bit6and
rewriting
it.
110
OPEN
15,8,15
Open
command
channel
120
OPEN
5,8,5,"#"
Open
direct
access
channel
130
PRINT#15,"Ul";5;0;18;l
Read
Track
18,
Sector
1
140
PRINT#15,"B-P";5;2
PointtoByte
2 of
the
buffer
150
GET#5,A$:IF
A$=""THENA$=
CHR$(0)
Readitinto
memory
160A=
ASC(A$)OR64
Turnonbit6to
lock
170
PRINT#15,"B-P";5;2
PointtoByte2again
180
PRINT#5,CHR$(A);
Overwrite
itinbuffer
190
PRINT#15,"U2";5;0;18;l
Rewrite
buffer
to diskette
200
CLOSE
5
Tidyupafter
210
CLOSE
15
220
END
After
the
above
programisrun,
the
first
fileonthat
diskette
cannolongerbeerased.
If
you
later
needtoerase
that
file,
re-run
the
same
program,
but
substitute
the
revised
line
160
belowtounlock
the
file
again:
160A=
ASC(A$)
AND
191
Turn
off
bit6to
unlock
ALLOCATING
BLOCKS
Once
you
have
written
something
inaparticular
sectorona
diskette
with
the
help
of
direct
access
commands,
you
may
wishtomark
that
sectoras"already
used,"tokeep
other
files
from
being
written
there.
Blocks
thus
"allocated"
willbesafe
until
the
diskette
is
validated.
FORMAT
FOR
BLOCK-ALLOCATE
COMMAND:
PRINT#15,<tBLOCK-ALLOCATE";drive
#;
track
#;sector
#
usually
abbreviated
as:
PRINT#15,"B-A";drive
#;
track
#;sector
#
where
"drive#"is
the
drive
number,
always0on
the
1541,
and
"track#"and
"sector
#"
are the
track
and
sector
containing
the
block
of
data
to
be
read
into
the
file
buffer.
ALTERNATE
FORMAT:
PRINT#15,"B-A:";drive
#;
track
#;sector
#
EXAMPLE:
If
you
trytoallocate
a
block
that
isn't
available,
the
DOS
will
set
the
error
message
to
number
65,NOBLOCK,
and
set
the
track
and
block
numbersinthe
error
message
to
70

the
next
available
track
and
block
number.
Therefore,
before
selecting
a
blocktowrite,
trytoallocate
that
block.Ifthe
block
isn't
available;
read
the
next
available
block
from
the
error
channel
and
allocate
it
instead.
However,donot
allocate
data
blocksinthe
directory
track.Ifthe
track
number
returned
is0,the
diskette
is
full.
Hereisa
program
that
allocates
a
placetostoreamessageona
diskette.
100OPEN15,8,15
110OPEN5,8,5,"#"
120
PRINT#5,"I
THINK
THEREFOREIAM"
130T=l:S=l
140
PRINT#15,"B-A";0;T;S
150
INPUT#15,EN,EM$,ET,ES
160IFEN=0
THEN
210
170IFENO65
THEN
PRINT
EN,EM$,ET,ES:STOP
180IFET=0
THEN
PRINT
"DISK
FULL":STOP
190IFET=18THEN
ET=
19:ES=0
200
T =
ET:S=ES:GOTO
140
210
PRINT#15,"U2";5;0;T;S
220
PRINT
"STORED
AT:",T,S
230
CLOSE
5:CLOSE
15
240
END
FREEING
BLOCKS
Open
command
channel
**
direct
access
"
Writeamessagetobuffer
Startatfirst
track§or
Try
allocating
it
Seeifit
worked
If
so,
we're
almost
done
"NO
BLOCK"
means
already
allocated
If
next
trackis0,
we're
outofroom
Don't
allocate
the
directory!
Try
suggested
track§or
next
Write
buffertoallocated
sector
Say
where
message
went
and
tidy
up
The
Block-Free
commandisthe
opposite
of
Block-Allocate.
It
freesablock
that
you
don't
need
any
more,
for
re-usebythe
DOS.
Block-Free
updates
the
BAMtoshow
a
particular
sectorisnotinuse,
rather
than
actually
erasing
any
data.
FORMAT
FOR
BLOCK-FREE
COMMAND:
PRINT#15,"BLOCK-FREE'';drive
#;track
#;sector
#
abbreviated
as:
PRINT#15,"B-F";drive
#;track
#;sector
#
where
"drive#"is
the
drive
number
(always0on
the
1541),
and
"track#"and
"sector
#"
are
respectively
the
track
and
sector
numbers
containing
the
desired
blockofdata
to
be
read
into
the
file
buffer.
ALTERNATE
FORMAT:
PRINT#15,"B-F:";drive
#;track
#;sector
#
71

CHAPTER
8
INTERNAL
DISK
COMMANDS
Expert
programmers
can
give
commands
that
directly
alter
the
workings.pf
the
1541,
muchasskilled
programmers
can
alter
the
workingsofBasic
inside
the
computer
with
Peeks,
Pokes
and
Sys
calls.Itis
also
possibletowrite
machine
language
programs
that
load
and
run
entirely
within
the
1541,
eitherbywriting
them
into
disk
memory
from
the
computer,orby
loading
them
directly
from
diskette
into
the
desired
disk
memory
buffer.
In
use,
thisissimilartoloading
and
running
machine
language
programsinyour
computer.
As when
learningtouse
Peek(),
Poke
and
Sysinyour
computer,
extreme
caution
is
advisedinusing
the
commandsinthis
chapter.
They
are
essentially
machine
language
commands,
and
lack
allofBasic's
safeguards.
If
anything
goes
wrong,
you
may
have
to
turn
the
disk
drive
off
andonagain
(after
removing
the
diskette)
to
regain
control.Donot
practice
these
commandsonany
important
diskette.
Rather,
makeaspare
copy and
work
with
that.
Knowing
howtoprograma6502inmachine
language
will
help
greatly,
and
you
will
also
needagood
memory
mapofthe
1541.Abrief
1541
map
appears
below.
Location
0000-00FF
0100-01FF
0200-02FF
0300-07FF
1800-180F
1C00-1C0F
C100-F258
F259-FE66
FE67-FE84
FE85-FEE6
FEE7-FF0F
FFE6-FFFF
1541
MEMORY
MAP
Purpose
2KofRAM
memory
Zero
page
work
area:
job queue,
important
variables
&
pointers
Stack
work
area
Command
buffers&tables:
channels,
parser,
output,
variables
Data
buffers
0-4,1per
pageofmemory.
Input/Output
chips
6522
VIA:
I/Otocomputer
65?2
VIA:
I/Otodisk
controller
Disk
Operating
System
ROM
Interface
Processor:
receive&interpret
commands
from
computer
Floppy
Disk
Controller:
executes
IP's
commands,
controls
mecha
nism
IRQ
handler:
switches
fromIPto
FDC&back
every10ms.
ROM
tables&constants
Patch
area
JMP
table:
User
command
vectors
73

Other
Resources:
More
detailed
information
about
Commodore
disk
drives
canbefoundinthese
books:
Inside
Commodore
DOS,byImmers&Neufeld
(Datamost,
cl984)
The
Anatomyofthe
1541
Disk
Drive,byEnglisch&Szczepanowski
(Abacus,
cl984)
Programming
the
PET/CBM,byWest
(Level
Limited,
cl982)
The
PET
Personal
Computer
Guide,byOsborne&Strasmas
(Osborne/McGraw-Hill,
c
1982)
MEMORY-READ
The
disk
contains
16KofROM
(Read-Only
Memory),aswellas2KofRAM
(Read-
Write
Memory).
You
can
get
direct
accesstoany
location
within
these,orto
the
buffers
that
the
DOS
has
setupin
RAM,byusing
memory
commands.
Memory-Read
allows
you
to
select
which
byteorbytestoread
from
disk
memory
into
the
computer.
The
Memory-
Read
commandisthe
equivalent
of
.the
Basic
Peek()
function,
but
reads
the
disk's
memory
insteadofthe
computer's
memory.
Note:
Unlike
other
disk
commands,
thoseinthis
chapter
cannotbespelled
out
in
full.
Thus,MRis
correct,
but
MEMORY-READisnotapermitted
alternate
wording.
FORMAT
FOR
THE
MEMORY-READ
COMMAND:
PRINT#15,t4M-R"CHR$(<address)CJ4R$(>address)CHR$(#
of
bytes)
where
"<address"isthe
low
order
pari,
and
">address"isthe
high
order
partofthe
addressindisk
memorytobe
read.Ifthe
optional
t4#ofbytes"isspecified,
it
selects
'how
many
memory
locations
will
be
read
in,
from
1-255.
Otherwise,
1
character
will
be
read.Ifdesired,
a
colon
(:)
may
follow
M-R
inside
the
quotation
marks.
ALTERNATE
FORMAT:
PRINT#15,t4M-R:"CHR$(<address)CHR$(>address)CHR$(#
of
bytes)
The
next
byte
read
using
the
Get#
statement
through channel
#15
(the
error
channel),
will
be
from
that
address
in
the
disk
controller's
memory,
and
successive
bytes
willbefrom
successive
memory
locations.
Any
Input#
from
the
error
channel
will
give
peculiar
results
when
you're
using
this
command.
This
can be
clearedupby
sending
any
other
commandtothe
disk,
except
another
memory
command.
74

EXAMPLES:
To
see
how
many
tries
the
disk
will
maketoreadaparticular
sector,
and
whether
"seeks"
one-half
tracktoeach
side
willbeattemptedifa
read
fails,
and
whether
t4bumps"totrack
one
and
back
willbeattempted
before
declaring
the
sector
unreadable,
we
can*use
the
following
lines.
They
will
readaspecial
variable
in
the
zero
pageofdisk
memory,
called
REVCNT.Itis
locatedat$6A
hexadecimal
($6A
hexadecimal
=
6x16
+
10=106).
110
OPEN
15,8,15
120
PRINT#
15,''M-R"CHR$(
106)CHR$(0)
130
GET#15,G$:IFG$=""THENG$=
CHR$(0)
140G=ASC(G$)
150B=GAND
128:B$="ON":IFBTHENB$=
"OFF"
160S=GAND
64:S$="ON":IFSTHENS$=
"OFF"
170
T =GAND
31:PRINT"#OF
TRIES
IS";T
180
PRINT
"BUMPS
ARE";B$
190
PRINT
"SEEKS
ARE";S$
200
CLOSE
15
210
END
Open
command
channel
SameasG=PEEK(106)
Check
bit
7
Check
bit
6
Check
bits
0-5
and
give
results
Tidyupafter
Here'samore
general
purpose
program
that
reads
oneormore
locations
anywhereindisk
memory:
110OPEN15,8,15
120
INPUT"#OFBYTESTOREAD(0=
END)";NL
130IFNL<1
THEN
CLOSE
15:END
140IFNL>255THEN120
150
INPUT"STARTINGATADDRESS";AD
160AH=
INT(AD/256):AL
=
AD-AH*256
170PRINT#15,"M-R"CHR$(AL)CHR$(AH)
CHR$(NL)
180
FOR
1=1TONL
190:GET#15,A$:IFA$=""THENA$=
CHR$(0)
200:
PRINT
ASC(A$);
210
NEXT
I
220
PRINT
230
GOTO
120
Open
command
channel
Enter
numberofbytes
wanted
unless
done
or
way
outofline
Enter
starting
address
Convertitinto
disk
form
Actual
Memory-Read
Loop
til
have
all
the
data
printingitaswego
Forever
MEMORY-WRITE
The
Memory-Write
commandisthe
equivalent
of
the
Basic
Poke
command,
but
has
its
effectindisk
memory
insteadofwithin
the
computer.
M-W
allows
youtowriteupto
34
bytesata
time
into
disk
memory.
The
Memory-Execute
and
some
User
commands
can
be
usedtorun
any
programs
written
this
way.
75

FORMAT
FOR
THE
MEMORY-WRITE
COMMAND:
PRINT#
15,*'M-W'CHR$(<address)CHR$(>address)CHR$
(#ofbytes)CHR$(data
byte(s))
where
"<address"isthe
low
order
part,
and
t4>address"
is
the
high
order
partofthe
addressindisk
memorytobegin
writing,
*'#ofbytes"isthe
numberofmemory
locations
that willbewritten
(from
1-34),
and
"data
byte"is1ormore
byte valuestobe
written
into
disk
memory,
eachasa
CHR$()
value.Ifdesired,
a
colon
(:)
may
follow
M-
W
within
the
quotation
marks.
ALTERNATE
FORMAT:
PRINT#
15/
'M-W:'
'CHR$(<address)CHR$(>address)CHR$
(#ofbytes)CHR$(data
byte(s))
EXAMPLES:
We
can
use
this
linetoturn
off
the
"bumps"
when
loading
DOS-protected
programs
(i.e.,
programs
that
have
been
protected
against
being
copiedbycreating
and
checking
for
specific
disk
errors).
PRINT#15,ttM-W"CHR$(106)CHR$(0)CHR$(l)CHR$(133)
The
following
line
can
be.usedtorecover
bad
sectors,
suchaswhenanimportant
file
has
been
damaged
and
cannotberead
normally.
PRINT#15,ttM-W"CHR$(106)CHR$(0)CHR$(l)CHR$(31)
The
above
two
examples
maybevery
useful
under
some
circumstances.
They
are
the
equivalent
of
POKE
106,133
and
POKE
106,31
respectively,
butindisk
memory,
not
inside
the
computer.Asmentionedinthe
previous
section's
first
example,
location
106
in
the
1541
disk
drive
signifies
three
separate
activities
to
the
drive,
all
related
to
error
recovery.
Bit7(the
high
bit),ifset
meansnobumps
(don't
thump
the
drive
backtotrack
1).
Bit6,if
set,
meansnoseeks.Inthat
case,
the
drive
won't
attempttoread
the
half-track
above
and
below
the
assigned
tracktoseeifit
can
read
the
data
that
way.
The
bottom
6
bits
are
the
countofhow
many
times
the
disk
will
trytoread
each
sector
before
and
after
trying
seeks
and
bumps
before
giving
up.
Since31is
the
largest
number
that
can
be
expressed
in6bits,
thatisthe
maximum
numberoftries
allowed.
From
this
example,
you
can
see
the
valueofknowing
something
about
Peeks,
Pokes,
and
machine-language
before
using
direct-access
disk
commands,aswellastheir
poten
tial
power.
76

MEMORY-EXECUTE
Any
routineindisk
memory,
eitherinRAMorROM,
canbeexecuted
with
the
Memory-Execute
command.Itis
the
equivalent
of
the
Basic
Sys
calltoa
machine
language
programorsubroutine,
but
worksindisk
memory
insteadofwithin
the
com
puter.
FORMAT
FOR
THE
MEMORY-EXECUTE
COMMAND:
PRINT#15,4tM-E"CHR$(<address)CHR$(>address)
where
"<address"
is
the
low
order
part,
and
">address"
is
the
high
order
partofthe
addressindisk
memoryatwhich
execution
istobegin.
ALTERNATE
FORMAT:
PRINT#15/<M-E:"CHR$(<address)CHR$(>address)
EXAMPLE:
Hereisa
Memory-Execute
command
that
does
absolutely
nothing.
The
first
instruc
tionitexecutesisan
RTS,
which
ends
the
command:
PRIOT#15,"M-E"CHR$(88)CHR$(242)
A
more
plausible
use
for
this
command
would
be
to
artificially
trigger
an
errat
message.
Don't
forgettocheck
the
error
channel,oryou'll
miss
the
message:
PRIOT#15,''M-E"CHR$(201)CHR$(239)
However,
most
uses
require
intimate
knowledgeofthe
inner
workingsofthe
DOS,
and
preliminary
setup
with
other
commands,
suchasMemory-Write.
BLOCK-EXECUTE
This
rarely-used
command
will
loadasector
containing
a
machine
language
routine
intoamemory
buffer
from
diskette,
and
executeitfrom
the
first
location
within
the
buffer,
untilaReTurn
from
Subroutine
(RTS)
instruction
ends
the
command.
FORMAT
FOR
THE
BLOCK-EXECUTE
COMMAND:
PRINT#15,"B-E'';channel
#;drive
#;track
#;sector
#
where
"channel#"is
the
channel
number
specified
when
the
file
into
which
the
block
willbeloaded
was
opened,
"drive#"is
the
drive
number
(always0on
the
1541),
and
"track#"and
"sector#"are
respectively
the
track
and
sector
numbers
containing
the
desired
block of
datatobe
loaded
into
the
file
buffer
and
executed
there.
77

ALTERNATE
FORMATS:
PRINT#15,44B-E:'';channel
#;drive
#;track
#;sector
#
PRINT#15,44B-E:channel
#,drive
#,track
#,sector
#"
EXAMPLES:
Assuming
you've
writtenamachine
language
program
onto
Track1,Sector8of
a
diskette,
and
would
liketorunitin
buffer
number1in
disk
memory
(starting
at
$0400
hexadecimal,
you
coulddosoasfollows:
110
OPEN
15,8,15
Open
command
channel
120
OPEN
2,8,2,44#1"
Open
direct
access
channeltobuffer
1
130PRINT#15,44B-E";2;0;l;8
LoadTrack1,Sector8init&
execute
140
CLOSE
2
Tidyupafter
150
CLOSE
15
160
END
USER
COMMANDS
Most
User
commands
are
intendedtobe
usedasmachine
language
JMP
or Basic
SYS
commandstomachine
language
programs
that
reside inside
the
disk
memory.
However,
someofthem
have
other
usesaswell.
The
Userl
and
User2
commands
are
used
to
replace
the
Block-Read
and
Block-Write
commands,UIre-starts
the
1541
without
changing
its
variables,
UJ
cold-starts
the
1541
almostasifithad
been
turned
off
and
on
again,
and
UI-
speedsupthe
1541
when
used
with
the
VIC20only.
(Note:
VIC20owners
don't
havetouse
UI-;
the
1541
works
with
the
VIC
20,
withorwithout
this
command.)
User
Command
Function
UIorUA
replaces
Block-Read
U2orUB
replaces
Block-Write
U3orUC
JMP
$0500
(sameasSYS
5*256,
but
within
the
1541
itself.)
U4orUD
JMP
$0503
(SYS
5*256+3)
U5orUE
JMP
$0506("
5*256+6)
U6orUF
JMP
$0509
(*'
5*256+9)
U7orUG
JMP
$050C(4<
5*256
+12)
U8
or
UH
JMP
$050F
(t4
5*256+15)
U9
or
UI
1541
NMI
(non-maskable
interrupt—warm
start)
U:
or
UJ
1541
reset
(cold
start,
allow2seconds
before
next
command.)
UI+
restore
1541tousual
speed
UI-
speed
1541
up
by
25%
when
used
with
VIC
20
only.
By
loading
these
memory
locations
with
another
machine
language
JMP
command,
such
as
JMP
$0520,
you
can
create
longer
routines
that
operate
in
the
disk's
memory
along
withaneasy-to-use
jump
table.
78

APPENDIX
A:
CHANGING
THE
DEVICE
NUMBER
SOFTWARE
METHOD
One
waytotemporarily
change
the
device
numberofa
disk
driveisviaaprogram.
When
powerisfirst
turned
on,
the
drive
readsanI/O
location
whose
valueiscontrolled
byajumperonits
circuit
board,
and
writes
the
device
numberitreads
there
into
memory
locations
119 and
120.
Any
time
thereafter,
you
may
write
over
that
device
number
with
a
new
one,
which
willbeeffective
untilitis
changed
again,orthe
1541isreset.
FORMAT
FOR
TEMPORARILY
CHANGING
THE
DISK
DEVICE
NUMBER:
PRINT#15,''M-W"CHR$(119)CHR$(0)CHR$(2)CHR$
(device#+
32)CHR$(device
#+64)
EXAMPLE:
Hereisa
program
that
sets
any
device
number
from
8-11:
10
INPUT'NEW
DEVICE
NUMBER';DV
20IFDV<8
OR
DV>11
THEN
10
30
OPEN
15,8,15
40
PRINT#15,"M-W"CHR$(119)CHR$(0)CHR$(2)CHR$(DV
+
32)CHR$(DV+64)
50
CLOSE
15
Note:
If
you
will
be
using
two
disk
drives,
and
want
to
temporarily
change
the
device
numberofone,
you
will
needtorun
the
above
program
with
the
disk
drive
whose
device
numberisnottobe
changed
turned
off.
After
the
program
has
been
run,
you
may
turn
that
drive
back
on.Ifyou
needtoconnect
more
than
two
drives
at
once,
you
will
needtouse
the
hardware
methodofchanging
device
numbers,
although
you
maybeabletogetbyinanemergencybyunplugging
the
serial
bus
cable
from
drives
whose
device
number
has
already
been
set
while
changing
others.
Thisisnot
recommended,
however,asthereisalways
dangerofdamaging
electronic
devices
when
pluggingincables
with
the
power
on.
81

24:
READ
ERROR
(byte
decoding
error)
The
dataorheader
has
been
read
into
disk
memory,
butahardware
error
has
been
createdbyan
invalid
bit
patterninthe
data
byte.
May
indicate
grounding
problems.
25:
WRITE
ERROR
(write-verify
error)
The
controller
has
detected
a
mismatch
between
the
data
writtentodiskette
and
the
same
dataindisk
memory.
May
mean
the
diskette
is
faulty.Ifso,
try
another.
Use
only
high
quality
diskettes
from
reputable
makers.
26:
WRITE
PROTECT
ON
The
controller
has-been
requested
to
writeadata
block
while
the
write
protect
sensoriscovered.
Usually
causedbywritingtoa
diskette
whose
write
protect
notch
is
covered
over
with
tapetoprevent
changing
the
diskette's
contents.
27:
READ
ERROR
(checksum
errorinheader)
The
controller
detectedanerrorinthe
header
bytesofthe
requested
data
block.
The
block
was
not
read
into
disk
memory.
May
indicate
grounding
problems.
Usually
unrecoverable.
28:
WRITE
ERROR
(long
data
block)
The
controller
attemptstodetect
the
sync
markofthe
next
header
after
writing
a
data
block.Ifthe
sync
mark
does
not
appearontime,
this
error
message
is
generated.
Itiscausedbya
bad
diskette
format
(the
data
extends
into
the
next
block)orbyahardware
failure.
29:
DISKIDMISMATCH
The
disk
controller
has
been
requestedtoaccessadiskette
which
has
not
been
initialized.
Can
also
occurifa
diskette
hasabad
header.
30:
SYNTAX
ERROR
(general
syntax)
The
DOS
cannot
interpret
the
command
senttothe
command
channel.
Typically,
thisiscausedbyan
illegal
numberoffile
names,oran
illegal
pattern.
Check
your
typing
and
try
again.
31:
SYNTAX
ERROR
(invalid
command)
The
DOS
does
not
recognize
the
command.Itmust
begin
with
the
first
character
sent.
Check
your
typing
and
try
again.
32:
SYNTAX
ERROR
(invalid
command)
The
command
sentislonger
than58characters.
Use
abbreviated
disk
commands.
33:
SYNTAX
ERROR
(invalid
file
name)
Pattern
matching
characters
cannotbeusedinthe
Save
commandorwhen
Opening
files
for
the
purposeofWriting
new
data.
Spell
out
the
file
name.
34:
SYNTAX
ERROR
(no
file
given)
The
file
name
was
left
out
ofacommand
or
the
DOS
does
not
recognize
it
as
such.
Typically,
a
colon
(:)
has
been
omitted.
Try
again.
84

APPENDIX
D:
DISK
COMMAND
QUICK
REFERENCE
CHART
General Format:
OPEN
15,8,15:PRINT#15,command:CLOSE
15
(Basic
2)
HOUSEKEEPING
COMMANDS
BASIC
2
BASIC
3.5
BOTH
NEW
COPY
RENAME
SCRATCH
INITIALIZE
VALIDATE
NEW
COPY
RENAME
SCRATCH
VALIDATE
INITIALIZE
FILE
COMMANDS
BASIC
2
BASIC
3.5
BOTH
LOAD
SAVE
LOAD
SAVE
CLOSE
GET#
INPUT#
OPEN
PRINT#
RECORD#
"NO:diskette
name,id"
"C0:new
file=0:old
file"
"R0:new
name=old
name"
"S0:file
name"
"10"
"VO"
HEADER*diskette
name,"
lid,DO
COPY
"old
file"TO"new
file"
RENAME
"old
name"TO"new
name"
SCRATCH
"file
name"
COLLECT
"10"
LOAD
"file
name",8
SAVE"0:filename",8
DLOAD
"file
name"
DSAVE
"file
name"
CLOSE
file
#
GET#file
#,variable
list
INPUT#file
#,variable
list
OPEN
file
#,8,channel
#,"0:file
name,file
type,direction"
PRINT#file
#,data
list
"P"+CHR$(channel
#)+CHR$(<record
#)
+
CHR$(>record
#)+CHR$(offset)
DIRECT
ACCESS
COMMANDS
BLOCK-ALLOCATE
BLOCK-EXECUTE
BLOCK-FREE
BUFFER-POINTER
BLOCK-READ
BLOCK-WRITE
MEMORY-EXECUTE
MEMORY-READ
MEMORY-WRITE
USER
"B-A";O;track
#;sector
#
"B-E";channel
#;O;track
#;sector
#
"B-F";O;track
#;sector
#
"B-P";channel
#;byte
"Ul";channel
#;O;track
#;sector
#
"U2";channel
#;O;track
#;sector
#
"M-E"CHR$(<address)CHR$(>address)
"M-R"CHR$(<address)CHR$(>address)CHR$(#
of
bytes)
"M-W"CHR$(<address)CHR$(>address)CHR$(#
of
bytes)
CHR$
(data
byte)
"Ucharacter"
92