c1541II Manual
c1541II Manual
DISK
El
DRIVE
D '"
users guide
COMMODORE
1541-II
DISK DRIVE COMMODORE
USER'S GUIDE 1541-II
This manual contains copyrighted and proprietary information. No
part of this publication may be reproduced , stored in a retrieval
system, or transmitted in any form or by any means, electronic , me-
DISK DRIVE
chanical, photocopying, recording or otherwise, without the prior
written permission of Commodore Electronics Limited. USER'S GUIDE
USER'S MANUAL STATEMENT
WARNING : This equipment has been certified to comply with the limits for
a Class B computing device, pursuant to subpart J of Part 15 of the Federal
Communications Commission 's rules, which are designed to provide rea-
sonable protection against radio and television interference in a residential
installation. If not installed properly, in strict accordance with the manufac-
turer's instructions, it may cause such interference. If you suspect interfer-
ence, you can test this equipment by turning it off and on . If this equipment
does cause interference, correct it by doing any of the following .
• Reorient the receiving antenna or AC plug.
• Change the relative positions of the computer and the receiver.
• Plug the computer into a different outlet so the computer and
receiver are on different circuits.
CAUTION : Only peripherals with shield-grounded cables (computer input-
output devices, terminals, printers, etc.), certified to comply with Class B
limits, can be attached to this computer. Operation with non-certified
peripherals is likely to result in communications interference.
(:commodore
COMPUTERS
TABLE OF CONTENTS
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
The advantages of a disk drive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Features of the 1541 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
How to use this book . . • . . . . • . . . . . . . . . . . . . . . . . . . . . . . • . . . . . . . . . . • 2
Basic Operating Steps. . . . . . . . . • . . . . • . . . . . . . . . • . . . . . . . . . . . • . . . . . . 2
Specifications of the 1541 Disk Drive. . . . . . . . . . . . . . . . . . . . . . • • . . . . . . 4
The 1541 disk drive greatly increases the speed , storage capacity, flexibility and reliabil-
ity of your Commodore computer. As you use the 1541 disk drive , you will appreciate its
superiority to the cassette recorder you may have useq before and to disk drives offered for
other brands of computers .
The 1541-D disk drive ia fully compattl>le with the commodore 1541 disk drive, therefore
we may often omit the "-II" auftlx throughout the remainder of thia manual.
• Speed
If you have used a cassette recorder for data storage, you probably know it can take up
to an hour just to search one long cassette tape looking for a specific program. With the
1541 disk drive, a list of all the programs on a diskette appears on your screen in
seconds . The speed of program loading is also greatly improved. It takes the 1541 only
a minute to load a large program that would take a half-hour to load from tape.
• Reliability
Reliability is another reason for choosing a disk drive. It is all too common for a cassette
user to accidentally erase a valuable program by saving a new program on top of the old
one, without realizing it. The 1541 disk drive automatically verifies everything it
records .
Overall , using a disk drive makes for easier and more powerful computing .
The 1541 is one of the most affordable disk drives on the market. Compared to
competitors, the 1541 has high capacity , and even higher intelligence . It is one of the most
cost-effective disk drives available. Most home and personal computers that use a disk
take at least !OK of RAM memory from the computer to hold a disk operating system
(known as a DOS .) This large program must be in memory the whole time the disk is
bei_ng used , and much of it must also be kept on every diskette.
The Commodore 1541 works differently and more effectively . It contains its own
built-in microcomputer to control its various operations , along with enough ROM and
RAM memory to operate without any help from the computer. Commodore 's DOS
"lives" entirely inside the disk drive , and does not require any internal memory in the
computer to do its work , nor does it have to be loaded before use like DOS on other
computers . It is so independent that once it begins working on a command , it will
complete it while the computer goes on to some t)ther task, effectively allowing you to do
two things at once .
Another key advantage of the Commodore 1541 over disk drives for other computers Once you've mastered the basic steps however, yoq will need to refer to the rest of
is its dynamic allocation of disk space. Many other disk drives make you think about this manual in order to make full use of the 1541 's features . In fact, before you begin, you
every program you save . Where can I store it on this diskette, and should I pack the disk should take a look at the following short sections, which offer precautions on hanclling the
first? (Packing is the process of moving all the leftover work areas to the end of the equipment: "Simple maintenance tips," "Safety rules for diskette care," and " Safety
diskette's storage space.) All this is handled automatically on Commodore disk drives. rules for removing diskettes."
The 1541 disk drive always knows where the next program will go, and automatically fits 1. Unpack, hook-up, and turn on the disk drive.
it into the best available spot. There's no shortcut through this part. You'll have to read this section to find out
Diskettes created on the 1541 may be read by several other Commodore disk what connects to what, when to : urn everything on, and bow to empty the drive.
drives, including the former 1540, 2040, and 4040, and the 2031. It is usually possi- If you run into any problems at this point, refer to the Troubleshooting Guide.
ble, though not recommended, to write data to any one of these drives from any of
the others. Gently insert a pre-programmed diskette.
The 1541 communicates with the computer and other devices over a cable and For the purpose of demonstration, use the Test/Demo diskette that was included
interface known as the Commodore serial bus. It is patterned after the IEEE-488 with the disk drive.
bus used on Commodore's PET and CBM models, except that the serial version If you run into any problems at this point, refer to Chapter 2, "Inserting a
only uses one wire for data. The two serial ports on the 1541 allow several devices Diskette."
to be connected together at once, each plugged into the next in "daisy chain" fash-
ion. Up to 4-disk drives and 2 printers can be connected this way. 3. Type: LOAD "HOW TO USE",8 (for Basic 2)
DLOAD "HOW TO USE"(for Basic 3.5)
HOW TO USE THIS BOOK Press: RETURN
HOW TO USE is the name of a particular program on the Text/Demo diskette. To
This book is divided into two main parts. The first part gives you the information you load a different BASIC program, substitute the name of that program inside the
need to use the 1541 effectively, even if you know little or nothing about programming. quotation marks.
This part of the book tells you how to set up the system, how to prepare diskettes for use, If you want to load a program that isn't written in BASIC language, you must
how to read a directory, and how to load programs. Part two of the book is for advanced use the Basic 2 command and add the following after the 8 in that command: ,l
users and those who would like to become advanced users. This part provides more If you run into any problems at this point, refer to Chapter 2, the section enti-
advanced commands, tells about the different files the 1541 uses, and how to manage tled "Loading a Packaged Program."
them, as well as giving a few hints for machine language programmers.
Both beginning and advanced users will find valuable information in the appendi- 4. After you perform step 3, the following will appear on the screen:
ces--a quick reference list of disk commands, a list of disk error messages and what they
mean, a glossary of words used in this manual, how to use two or more disk drives at SEARCHING FOR HOW TO USE
once, and explanations of some programs on the Test/Demo diskette packed with your LOADING
1541. READY
Since owners of four different Commodore computers use the 1541, we have
separated several explanations into two versions, depending on which Basic your com- At this point, type RUN and press the RETURN key and follow the directions
puter uses. If you have a VIC 20 or Commodore 64, please read the pages marked Basic for the program.
2. Those with the Commodore 16 or the Plus/4 should read pages marked Basic 3 .5. For
many commands, there will be an added page or two of further comments and advanced
techniques. Feel free to skip anything you don't understand on those pages now, and come
back later.
If you're like most people, you're anxious to start using your new disk drive
right away. In view of that, we have outlined the basic steps you need to know in
order to get started.
2 3
SPECIFICATIONS OF THE 1541 DISK DRIVE PART 1: GUIDE TO OPERATION
CHAPTER 1
STORAGE
DISK DRIVE
Total formatted capacity 174848 bytes per diskette
Maximum Sequential file size UNPACKING
168656 bytes per diskette
Maximum Relative file size 167132 bytes per diskette
Records per file The first thing you will need to do with your disk drive is unpack it. Inside the carton
65535
Fil~s per diskette
in which you found this manual, there should also be: a 1541 disk drive, supply power
144
Tracks per diskette a black cable to connect the disk drive to the computer, a demonstration diskette . and
35
Sectors per track a warranty card to be filled out and returned to Commodore .
17-21
Sectors per diskette Please don't connect anything until you've read the next three pages! It could save
683 total
you a lot of trouble .
664 free for data
Bytes per sector 256
ELECTRICAL REQUIREMENTS
Three wire-grounded detachable power cable . DRIVE INDICATER (GREEN LED)
Voltage U.S. 100-120 VAC
LIGHT: ACTIVE /FLASH : ERROR
Export 220--240 VAC
Frequency U.S . 60 HZ
Export 50 HZ POWER INDICATER (RED LED)
Power used 25 Watts llGHT : POWER ON
MEDIA
Any good quality 5Y. inch diskette may be used (Commodore diskettes are recom-
mended) .
THE PRODUCT DOES NOT NECESSARILY RESEMBLE THE PICTURE INSIDE THE USER"S MANUAL.
5
4
EMPTY THE DRIVE After plugging the power supply into the disk drive and a suitable outlet, find the black
cable that goes from the disk drive to the computer. lt is called a serial bus cable to
First, it is very important to be sure nothing is inside the disk drive . If you tum the describe the way the computer, and other accessories communicate with each other
power off or oil with a diskette_in the drive, you could lose its contents and have to re- through its wires . It has an identical 6-pin DIN connector at each end, which like the
record it . Since you wouldn't like having to do that, always check to be sure nothing is power connector can only go in one way-with the dimple in the side of the plug facing
inside the drive before turning it off or on . up .
When you first unpack the disk drive, you will find a cardboard shipping spacer To plug in the serial bus cable, find the dimple on the side of the metal part of the
inside. Following the instructions below, pull it out as though it were a diskette, but don't plug and tum that side up. Then push it straight into one of the two serial bus connectors
throw it away . You will want to put it back inside the slot any time you move or hip the on the back of the disk drive . The other end goes into the similar connector on the back of
disk drive later. your compuU:r, marked "serial bus." lf another accessory, such as a printer, is already
To check whether the drive is empty (Fig. 1), simply rotate the lever on the front connected there, unplug the other device's cable from the computer, and attach it to the
of the disk drive counter-clockwise until it stops, one-quart~r tum at most. Then reach spare serial bus connector on the back of the 1541 . Then install the serial cable from the
inside the long slot the lever covers when it points down, and pull out any diskette you 1541 in the serial bus connector on the back of the computer (Fig 3.A.)
f"md there. If you have more than one disk drive, each added disk drive's serial bus cable is
plugged into the second serial bus connector on the back of the previous disk drive, like a
CONNECTING THE CABLES
daisy chain (Fig 3.B) . However, don't connect the other(s) until you've learned how to
change their device numbers, as no two disk drives can have the same device number.
With the power supply, the power cable plugs into the back of the disk drive at one
We'll cover ways of changing disk device numbers in Appendix A. Until you are ready to
end, and into a grounded (3-prong) outlet at the other end .It will only go in one way . Before
read that section, you may find it easier to leave your extra drive(s) unconnected .
you plug 1t in though, make sure that your entire computer system is turned off. The disk
drive's on/off switch is in the back, on the right side (when viewed from the back). It is
~ff when the botton ~alf is pushed inward. Leave your whole system off until everything TURNING ON THE POWER
is connected. We will tell you when it is safe to tum it on.
With everything hooked up, and the disk drive empty, it is time to tum on the power.
You can tum on the power to the disk and other devices on the serial bus (connected via
Fig 2. Back Panel
serial cables) in any order you like. Just be sure to either tum on the power to the computer
DIP SWITCH FOR CHANGING itself last, or to. use a multiple outlet power box with a master switch to tum everything off
POWER SWITCH
and on at once. When everything is on, including the computer, the disk drive will go
DEVICE NUMBER ON/ OFF through a self check for a second or so, to be sure it is working correctly . After the drive is
satisfied with its own health, it will flash the green light once, and the red power-on light
will glow continuously. At the same time, the oomputer will be going through a similar
self-test, and displaying its hello message on your TV or video monitor. Once the green
light on the disk drive has flashed and gone out, it is safe to begin working with the drive.
If the light doesn't go out, but continues to flash, you may have a problem. Refer to the
troubleshooting guide for help.
SERIAL INTERFACE POWER
DEVICE
0 OFF 0
SERIAL PORT
POWER CORO SOCKET
CONNECTORS FOR
INTERFACE CABLES
6 7
TROUBLESHOOTING GUIDE
Power supply
AC
Green error light The disk drive is Tum the system·off for
on anve nashes failing its power-on a minute and try again .
Single continously on self-test lf it repeats, try again
Fig 3.A Floppy Disc Hookup power-up, before with the serial bus
any disk commands disconnected . If it
.have been given still repeats , call your
dealer. If unplugging
the serial cable made a
difference, check the
cable for proper
connection at both ends.
This can also be caused
by some cartridges on
the C-64 and always by
a I 6K cartridge on the
Personal Computer Serial Cable VIC 20. Remove the
cartridge and power-up
the disk drive again to
determine where the
problem is.
(The principle behind unplugging the serial cable is " divide and conquer." The drive can do its
power-on test even when not connected to a computer. If it succeeds that way, then the problem is
probably in the cable or the rest of the system, not the 1541 .)
Power supply
Twin
Fig 3.8 Floppy Disc Hookup
8
9
TROUBLESHOOTING GUIDE SIMPLE MAINTENANCE TIPS
Symptom Cause Remedy Your 1541 should serve you well for years to come, but there are a few things you
Prograrlls won't load, and Serial bus cable Be sure serial bus cable can do to avoid costly maintenance .
computer says "Dl;lVICE not well connected, or is correctly inserted
NOT PRESENT ERROR ." disk not turned on. and disk drive is turned 1. Keep the drive well-ventilated . Like a refrigerator, it needs a few inches of air
on circulation on all sides to work properly .
Programs won't load, but Anolher device on the Unplug all other devices 2. Use only good quality diskettes . Badly-made diskettes could cause increased wear on
computer and disk drive serial bus may be on the serial bus. If the drive's read/write head . If a particular diskette is unusually noisy in use, it is probably
give no error message. interfering. that cures it, plug them causing added wear, and should be replaced.
in one at a time. The 3. Avoid using programs that "thump" the drive as they load . Many commercial
one just added when the
trouble repeats is most
programs, and diskettes that are failing, cause the disk drive to make a bumping or
likely the problem. chattering noise as it attempts to read a bad sector. If the diskette can be copied to a fresh
diskette, do so immediately. If it is protected by its maker against copying, the thumping
Also , trying to load a
machine language program is intentional and will have to be endured. Be aware, however, that excessive thumping,
into BASIC space will especially when the drive is hot, caused some older 1541 's to go out of alignment and led
cause this problem. to costly repairs . Current 1541 's have been redesigned to prevent the problem .
(Such devices may not be turned on properly, or may have conflicting device numbers. Only one Note: the "Memory-Write" example in Chapter 8 temporarily turns off the bumps.
device on the bus can have any one device number.) 4. It would be a good idea to have your 1541 checked over about once a year in normal
Programs won't load A disk error has Check the disk error use. Several items are likely to need attention: the felt load pad on the read/write head may
and disk error light occurred. channel to see why the be dirty enough to need replacement, the head itself may need a bit of cleaning (with 91 %
flashes. error occurred. Follow isopropyl alcohol on a cotton swab), the rails along which the head moves may need
the advice in Appendix B
to correct it. lubrication (with a special Molybdenum lubricant, NOT oil), and the write protect sensor
may need to be dusted to be sure its optical sensor has a clear view. Since most of these
(Be sure to spell program names exactly right, as the disk drive is very particular, even about spaces
and punctuation marks, and will not load a program unless you call it exactly the same thing it was chores require special materials or parts, it is best to leave the work to an authorized
called when it was saved on the diskette.) Commodore service center. If you wish to do the work yourself, ask your dealer to order
Your own programs Load Either the diskette you Try another copy of the
the 1541 maintenance guide for you (part number 990445), but he aware that home repair
fine, but commercial are loading is faulty, troublesome programs. If of the 1541 will void your warranty.
programs and those (some mass-produced several programs from
from other 1541 owners diskettes are) or your several sources always~
fail to load. disk drive is misaligned. fail to load, have your
dealer align your
disk drive.
Your own programs Iha! Older diskettes have See the section on safety
used IQ Load won't been damaged . rules for diskette care.
any more, but programs Recopy from backups.
saved on newly-formatted The disk drive has gone
diskettes still work. out of alignment. Have your dealer align
your disk drive.
The disk drive powers Hardware failure (RAM, Have your dealer send it
up with the activity ROM, PCB). out for repair.
light blinking.
10 11
SAFETY RULES FOR DISKETTE CARE
CHAYfER2
DISKETIES I. 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
WHAT IS A DISKETTE? from temperatures either too hot or too cold for you to work in for extended periods.
2. When not in the drive, diskettes should be stored upright inside their paper jackets. Do
Before we actually begin using the drive, let' s take a moment to look at the not allow them to become bent or folded . Since the working part of the diskette is on
Test/Demo diskette packed with the disk drive. Tc;> do this, grasp it by the label, which the bottom , never set it down on a table top, or other place where dust or moisture
should be sticking out of the paper jacket. Then pull it out of the jacket which keeps it free might affect it, and be especially careful to keep your fingers away from the opening~
of dust and other contaminants. (Save the jacket; the diskette should always be kept in its in the diskette cover.
jacket except when actually in use in the disk drive.) It is often called a floppy diskette , 3. Although some people sell kits intended to " double your diskette' s capacity " by
because it is flexible , even though it is not safe to bend diskettes . cutting an extra write-protect notch into a diskette , it is best not to use the other side of
A diskette is much like a cassette tape, but in the form of a circle and enclosed within the diskette on the 1541 drive, even if your diskette is labeled " double-sided ." Doing
a protective square plastic cover. As on a cassette tape, only a small exposed portion of so will cause added wear to your diskettes and drive, and may cost you an important
the magnetic recording surface is sensitive. You may touch the rest of the diskette any program some day .
time you like, but avoid touching the few small portions that are not covered by the 4. When buying diskettes , you may use any good quality 5 1/• inch diskette .
protective cover. Also, never try to remove this cover. Unlike the paper jacket, the plastic 5. Mak'e sure the diskette center hole is more or less centered in its opening before
diskette cover is intended to remain on permanently. inserting the diskette into the drive. Although the hub assembly will correctly center
Next, notice the notch on one side of the diskette (it may be covered by a piece of most any diskette, it would be very difficult to rescue data from a diskette recorded
tape) . This notch is called the write protect notch. When it is covered with the opaque tape with its hub off-center. One way to help center diskettes is to " tickle" the drive door
packed with blank diskettes, the disk drive cannot change the contents of that diskette. shut instead of slamming it down . By gently closing it part-way , and then opening a bit
Never remove the tape on the Test/Demo diskette. and then closing the rest of the way , you give the spindle more chances to center the
The label on the top of the diskette says "1541 Test/Demo" on it , and tells you diskette properly . Another way to ease diskette centering is to buy diskettes that come
which diskette you are using . Blank diskettes come with extra labels in addition to one with reinforced hubs . These hard plastic rings arouncl the hub opening make the
applied by the maker of the diskette. Use them to describe your own diskettes. diskette hub more rigid, and easier to center properly . ·
• At least two other parts of the diskette are worth mentioning: The hub and the access
slot . The hole in the center is called the hub. A cone-shaped spindle fills it when the drive INSERTING A DISKETTE
door is closed, and its edges are clamped. This' keeps them from slipping, when the
diskette spins at 300 RPM in use. To insert a diskette in a 1541 (Fig. 1), first open the drive door by rotating the door
The oval opening in the diskette opposite the label is called the access slot. It exposes lever counter-clockwise one quarter tum until it stops, with the lever level with the slot in
just enough of the diskette's surface for the read/write head and load pad inside the drive the front of the drive.
to touch a one inch long line from the center to the edge of the diskette' s working surface. Grasp the diskette by the side opposite the large oval access slot, and hold it with the
The bottom side of that slot is where all the information is written as the diskette spins . It label up and the write-protect notch to the left. Now insert the diskette by pushing it
is one place your fingers should never touch. straight into the slot, the access slot going in first and the label last. Be sure the diskette
goes in until it stops natµrally, with no part showing outside the drive, but you shouldn ' t
have to force or bend it to get it there.
ACCESS SLOT
With the diskette in position , seat it properly for use by twisting the door lever
clockwise one-quarter tum , vertically over the slot until it stops . If it does not move
z
VI easily, stop! You may have put the diskette in the wrong way, or incompletely . If that
m
:D happens, reposition the diskette until the door lever closes easily .
-i
z
-i
WRITE 0
PROTECT 0
NOTCH :D
~ <
c:::::::::J m
WHEN COVERED, DISKETTE =
CONTENTS CANNOT BE
ALTERED LABEL
A diskette needs a pattern of magnetic grooves in order for the drive's read/write
head to find th~ngs on it. This pattern is not on your diskettes when you buy them, but
adding it to a diskette is simple once you know to do it. Here is the procedure:
This Open command will be described more fully, in Chapters 4 and 5. For now, just
copy it as is, replacing only the parts given in lower case. These include: the device
14 15
number of the 1541, normally 8; the drive number, always 0 on the 1541; any desired
your format command . By leaving off the ID number, the fonnat command will finish in a
name for the diskette, up to 16 characters in length, followed by a 2 character diskette ID
few seconds instead of the usual 90 seconds .
number. The Close command is often optional; just don't Open that same file again
without Closing it the first time.
ORGANIZING A DISKETTE LIBRARY
EXAMPLE:
Though you may not believe it now , you will eventually have dozens, if not hundreds
OPEN 15,8, 15, "NO:MY FIRST DISK,01": CLOSE 15 of diskettes. You can ease life then by planning now . Assign each diskette a unique ID
number when you fonnat it. There are diskette cataloging programs you can buy , that
Note: the chattering or thumping noise you hear just after the disk New command store and alphabetize a list of all your file names, but are of limited value unless your
begins is entirely normal. The disk must be sure it is at track 1, which it assures by diskette ID numbers are unique.
stepping outward 45 times (on a 35 track diskette.) The noise you hear is the head At least two valid approaches are used in assigning ID numbers . One starts at 00 with
assembly hitting the track 1 bumper after its inevitable arrival. the first diskette , and continues upward with each new diskette, through 99, and then
onward from AA through U. . Another organizes diskettes within small categories , and
HOW TO PREPARE A NEW DISKETTE: BASIC 3.5 starts ihe ID number for each diskette in that category with the same first character, going
from 0 to 9 and A to Z with the second character as before . Thus, all "Tax " diskettes
A diskette needs a pattern of magnetic grooves in order for the drive's read/write could have ID numbers that begin with ''T. ' ' Either approach works well when followed
head to find things on it. This pattern is not on your diskettes when you buy them, but diligently.
adding it to a diskette is simple once you know to do it. Here is the procedure: While on this subject, may we suggest you choose names for diskettes on the same
basis, so they too will be unique, and descriptive of the files on them.
FORMAT FOR THE HEADER COMMAND
BACKUPS
HEADER "diskette name" ,lid,Ddrive #,Udevice #
When to do a Backup
Where "diskette name" is any desired name for the diskette, up to 16 characters in Although the 1541 is far more reliable than a cassette drive under most circum-
length; "id?' is a 2 character diskette ID number; "drive #" is the drive number, 0 if stances, its diskettes are still relatively fragile, and have a useful life of only a few years in
omitted (as it must be on the 1541); and "device#" is the disk's device number, assumed steady use. Therefore, it is important to make regular backups of important programs and
to be 8 if omitted . As described in the next page, "id" is optional if (.and only if) the files. Make a backup whenever you wouldn't want to redo your current work . Just as you
diskette has been previously formatted on a 1541. Also, the ID must be a string literal, not should save your work every half hour or so when writing a new program, so you should
a variable or expression, and may not include Basic reserved words. Thus, ",IFI" cannot also back up the dis~ette you're using at least daily while you are changing it frequently .
be used because If is a Basic keyword, and ",l(A$)" is not allowed because A$ is a In a business, you would make an archival bac;kup every time important information was
variable. " ,IA$" is allowed, but the ID number will be the letter "A" plus a dollar sign due to be erased, such as when a new accounting period begins .
($),not the contents of the variable A$ . If you need a variable ID number, use the Basic 2
How to do a Backup
form of the format command.
We have included programs on the TesVDemo diskette that can be used for similar
EXAMPLE: purposes. These programs are described further in Appendix E.
PRINT#4:CLOSE 4
One indicator you may occasionally notice on a directory line, after you begin saving If you would like to read a directory from within a program, you may do so. In Basic
programs and files, is an asterisk appearing just before the file type of a file that is O 3.5, simply include the DIRECTORY command in your Basic program. In Basic 2,
blocks long. This indicates the file was not properly closed after it was created, and that it however, and optionally in the others, you will have to Open the directory as though it
should not be relied upon. These "splat" files (as they are called in England) will we£a data file and read it character by character. See the discussion of Get# in Chapter 5
normally need to be erased from the diskette and rewritten. However, do not use the for more information .
Scratch command to get rid of them. They can only be safely erased by the Validate and
Collect commands. One of these should normally be used whenever a splat file is noticed ANOTHER WAY TO BE SELECTIVE
on a diskette. (All these commands are described in the next chapter.)
There are two exceptions to the above warning: one is that Validate and Collect Before discussing the pattern-matching options available for use in several disk
cannot be used on some diskettes that include direct access (random) files, and the other is commands, let's cover one more that is only usable in a directory . _Several different types
that if the information in the splat file was crucial and can't be replaced, there is a way to of files can coexist peacefully on the same diskette . By altering our directory load
rescue whatever part of the file was properly written. (This option is also described in the command, we can create a directory from the files of a single selected type . Thus , we
next chapter) . might request a list of all sequential data files (see Chapter 5), one of all the relative data
files (see Chapter 6), or one of only program files. To do this, simply add to the end of
your selective directory request the equals sign ( =) followed by the first letter of the file
type you want in your directory . For example, the Basic 2 command:
20
21
LOAD"$0:* = S" ,8 FORMAT FOR PATTERN MATCHING: EXAMPLES :
will load a directory of all sequential files, while the Basic 3.5 command: "expression*" "C-64*"
will display a directaF¥ consisting only of relative files beginning with the letter ''A''. "expression?expression'' "C?64 WEDGE"
The possible file types, and their abbreviations for this use are: or
Just as cassette users can load programs without giving a full name, disk users can
use special pattern matching characters to load a program from a partial name. The same
characters can also be used to provide selective directories. The two special characters
used in pattern matching are the asterisk (*) and the question mark (?). They act
something like a wild card in a game of cards. The difference between the two is that the
asterisk makes all characters in and beyond its position wild, while the question mark only
makes its own character position wild. Here are some examples, and their results:
LOAD "A*" ,8 loads the first file on disk that begins with an "A", regardless of
what follows. "ARTIST", "ARTERY", and "AZURE" would all qualify, but
"BARRY" wouldn't, even though it has an "A" elsewhere in its name.
DLOAD "SM?TH" (Basic 3.5) loads the first program that starts with "SM", ends
with "TH", and has one other character between. This would load "SMITH" or
"SMYTH'', but not "SMYTHE"
OPEN 8,8,2,"R?C*,S,R" We'll study Open in Chapter 5, but the pattern used here
means that the selected file will begin with an "R" and have a "C" in the third character
of its name .
DIRECTORY, "Q*" (Basic 3 .5) will load a directory of files whose names begin
with "Q" .
LOAD"*" ,8 and DLOAD "*"are special cases. When an asterisk is used alone as
a name, it matches the last file used . If none have been used yet on the current diskette
since turning on the drive, using the asterisk alone loads the first program on the diskette.
10 INPUT A$ : LOAD A$+'' * '', 8 loads any file whose name starts with the
characters entered in A$ .
22 23
PART TWO:
GUIDE TO ADVANCED OPERATION
AND PROGRAMMING
CHAPTER4
COMMANDS
COMMAND CHANNEL
Commodore disk drives expect to receive many of their instructions over what is
known as a command channel. Although we will not explain the concepts behind it until
Chapter 6, we will learn it to use it now, so you can give your 1541 disk the commands it
needs to do some essential chores.
To instruct the command channel, we use a Basic Open statement to the disk, with a
secondary address of 15. The usual form of this statement is:
OPEN 15,8,15
The first 15 is a file number, and could be any number from 1 to 255. It is used to
match the secondary address (the last number on the line), which is ·also 15 . The middle
number is the primary address, better known as the device number, and is normally 8
when talking with the 1541. A second disk drive would usually be 9, a third, 10 and so on.
Once the command channel has been opened, use the Basic Print# command to send
information to the disk drive, and Basic's Input# command to receive 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 Basic 2, you'll use both Print#l5 and Input#l5 extensively, to send housekeep-
ing commands to the disk and to check its error status. Basic 3.5 has built-in commands
for most of these chores. Even so, it will be good for those of yo'u with Basic 3.5 to see
how such commands are sent.
PRINT#l5 , "IO"
This command assumes we have already opened the file 15 to the command
channel. "10" can be replaced with any string expression that is a 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, "IO"
However, this only works for the first disk command given. After that, file 15 is
already open, and Opening it again would cause a "ALE OPEN" error. Added com-
mands are sent via Print# instead.
25
FORMAT FOR SENDING DISK COMMANDS PRINT DS$
or ?DS$
Print# 15 ,command$ either in immediate mode or within a program, and the current error status message of the
disk will be displayed on the screen. A message will be displayed whether there is an error
Examples: or not, but if there was an error, printing its message will also clear it from the disk
memory and turn off the error light on the disk drive.
Once the message is on the screen, you can look it up in Apwndix B to see what it
OPEN 15,8,15,"VO"
means, and what to do about it.
or
ERROR CHECK SUBROUTINE
PRINT#l5,"VO"
Since those of you who are writing programs should be checking the error status after
wher~ "device #" is the disk's device number, normally 8, and "command$" is any each disk command, you may want to include a small subroutine in each program to take
valid string expression . If it is not also a valid disk command, it will result in an error on care of the error channel. Here is one we use:
the disk drive . This is indicated by a flashing error light on the disk drive, and an error
message such as "31,SYNTAX ERROR" when the error channel is read as described on Basic 2 version: Basic 3.5 version :
the next two pages .
59980 REM READ ERROR CHANNEL 59990 REM READ ERROR CHANNEL
59990 INPUT#l5, EN,EM$,ET,ES 60000 IF DS> I THEN PRINT DS$:STOP
READING THE ERROR CHANNEL: BASIC 2
60000 IF EN> I THEN PRINT
EN ,EM$,ET ,ES:STOP 600 I0 RETURN
In Basic 2, there is no simple way to learn what is causing the error light to flash on
60010 RETURN
the disk drive without writing a small program. This, in tum, causes you to lose any
program variables already in memory . The reason for this is that the INPUT# command
The Basic 2 version assumes file 15 has already been opened earlier in the program, and
cannot easily be used in immediate mode (that is, without a line number).
that it will be closed somewhere else at the end of the program .
You will often need to be able to read the disk error channel , to see why the disk error
This subroutine reads the error channel and puts the results into the named variables .
light is flashing, and thereby tum the error light off again .
In the Basic 2 version, they are EN, EM$, ET, and ES, which stand for Error Number,
Here is a brief program to check for disk errors:
Error Message, Error Track and Error Sector respectively. Of the four, only EM$ has to
be a string, and you could choose other variable names, although these have become
10...0PEN 15,8,15
traditional for this use.
20 INPUT#l5 ,EN,EM$,ET,ES
. The Basic 3.5 version subroutine uses the reserved variables DS and DS$ already set
30 PRINT EN ,EM$,ET,ES
aside for this purpose. They are updated automatically by Basic whenever they are used .
40CLOSE 15
Otherwise, the two versions of the subroutine are equivalent.
Two error nu1T_1bers are harmless: 0 means everything is OK, and I tells how many
This little program reads the error channel into 4 Basic variables, and prints the
fil~s were erased by a Scratch command . If the error status is anything else, line 60000
results on the screen. A message will be displayed whether there is an error or not, but if
Pnnts the error message and halts the program. After you have repaired the damage, you
there was an error, this program will also clear it from disk memory and turn off the error
may then continue the program with Basic's Cont command .
light on the disk drive.
. Because this is a subroutine, you access it with the Basic Gosub command, either in
Once the message is on the screen, you can look it up in Appendix B to see what it
•mmediate mode or from a program . (For example, ' '200 GOSUB 59990" .) The Return
means, and what to do about it.
statement in line 60010 will jump back to immediate mode or the next statement in your
Program, whichever is appropriate.
READING THE ERROR CHANNEL: BASIC 3.5
In Basic 3.5, it is very easy to learn what is causing the error light to flash on the disk
drive, and no need to write a program . Simply type:.
26 27
HOUSEKEEPING HINTS
Note: the ' 'O:'' at the start of file names is a holdover from the days when all
Hint #1: It is best to open file IS once at the very start of a program, and only close it a1 Commodore disks had two drives in the same cabinet. Although the I S4 I will
the end of the program, after all other files have already been closed. Do this because normally default to drive 0 (not having a drive 1,) it is best to specify the drive
closing the command channel automatically closes all other disk files . By opening once a1 number whenever saving or writing a file . This avoids potential confusion in DOS
the start, the file is open whenever needed for disk commands elsewhere in the program (the Disk Operating System.)
Closing it at the end makes sure all disk files are properly closed without interrupting ani
other file commands .
Hint #2: If Basic halts with an error when you have files open, Basic aborts them withou1 SAVING PROGRAMS: BASIC 3.5
closing them properly on the disk. To close them properly on the disk, you must type:
Before you can save a program to diskette , the diskette must be formatted , as
OPEN IS,8 , lS :CLOSE IS described earlier. Saving to diskette is just like saving to cassette, except that the device
number of the disk drive is not optional.
This opens the command channel and immediately closes it, along with all other disk
files. Failure to close a disk file properly both in Basic and on the disk may result in losing FORMAT FOR THE DSA VE COMMAND
the entire file!
HINT #3: One disk error message is not always an error. Error 73, "CBM DOS 2.6 DSAVE "file name " ,Ddrive # ,Udevice #
IS41" will appear if you read the disk error channel before sending any disk commands
when you turn on your computer. This is a handy way to check which version of DOS you where "file name" is any string expression of up to 16 characters, optionally followed by
are using. However, if this message appears later, after other disk commands, it means the drive number (the "D" parameter, always 0 on the IS41), and the device number o(
there is a mismatch between the DOS used to format your diskette and the DOS in yow the disk drive (the "U" parameter) . If omitted, the drive number defaults to 0, and the
drive. device number to 8.
However, it will not work in copying programs that are not in the Basic text area,
HINT #4: To reset drive, type: OPEN IS,8,IS ,"UJ" Then wait until the drive activit) such as "DOS S. l" for the Commodore 64 . To copy it and similar machine language
LED is off and motor goes off, then type: CLOSE IS . This also applies to sending a UI + programs, you will need the .S command of the machine language monitor built into the
or a Ul - Commodore 16 and Plus/4 . To access a built-in monitor, type MONITOR . To exit · a
monitor, type X alone on a line.
SAVING PROGRAMS: BASIC 2
Before you can save a program to diskette, the diskette must be formatted , 35 FORMAT FOR A MONITOR SA VE
described earlier. Saving to diskette is just like saving to cassette, except that the device
number of the disk drive is not optional. S"drive #:file name",device # ,starting address ,ending address+ I
FORMAT FOR THE SA VE COMMAND where "drive#:" is the drive number, 0 on the IS41; "file name" is any valid file name
up to 14 characters long (leaving 2 for the drive number and colon); "device#" is a two
digit device number, normally 08 on the IS41 (the leading 0 is required); and the
SAVE "drive # :file name" ,device# addresses to be saved are given in Hexadecimal (base 16,) but without a leading dollar
sign ($). Note that the ending address listed must be I location beyond the last location to
where "file name " is any string expression of up to 16 characters, preceded by the drive be saved.
number (always 0 on the l S4 l) and a colon , and followed by the device number of th1
disk, normally 8. EXAMPLE:
However, it will not work in copying programs that are not in the Basic text area
such as "DOS S. I" for the Commodore 64 . To copy it and similar machine language Here is the required syntax to save a copy of "DOS S. l"
programs , you will need a machine language monitor program . Its u
for thi~ purpo~e is identical to the monitor save described on the next page unde S"O:DOS S. l ",08,CCOO, C FSA
Ba~ic 3.S.
28 29
SAVE WITH" REPLACE OPTION If the disk copy of the program differs even a tiny bit from the copy in memory,
«VERIFY ERROR" will be displayed, to tell you that the copies differ. This in itself
doesn't mean either copy is bad, but if they were supposed to be identical, one or the other
If a file already exists, it can't be saved again because the disk only allows one copy has a problem .
of any given file name per diskette. It is possible to get around this problem using the Naturally, there's no point in trying to verify a disk copy of a program after the
Rename and Scratch commands described later. However, if all you wish to do is replace original is no longer in memory . With nothing to compare to, an apparent error will
a program or data file with a revised version, another command is n;iore convenien~ . always be announced, even though the disk copy is always and automatically verified as it
Known as Save-with-replace , or @Save, this option tells the disk to replace any file 1t is written to the disk.
finds in the directory with the same name, substituting the new file for it.
FORMAT FOR THE VERIFY COMMAND:
FORMAT FOR SA VE WITH REPLACE: FORMAT FOR SA VE WITH REPLACE:
BASIC 2 BASIC 3.5 VERIFY " drive # :pattern" ,device #,relocate Hag
30 31
FORMAT FOR THE SCRATCH COMMAND: "pattern" can be any file name or combination of characters and wild card characters. _As
usual, "D" stands for drive number, which may only be 0 on the 1541 . If the dnve
PRINT# 15, "SCRA TCHO: pattern" number is omitted, 0 is assumed . Likewise , "U" stands for unit (device) number,
normally 8. If "U" is omitted, 8 is assumed .
or abbreviate it as: Thanks to the defaults , the usual form of the Scratch command becomes:
''pattern'' can be any file name or combination of characters and wild card characters. As SCRATCH "pattern"
usual , it is assumed that the command channel has -already been opened as file 15 .
Although not absolutely necessary, it is best to include the drive number in Scratch As a precaution, you will be asked:
commands.
If you check the error channel after a Scratch command, as tlescribed in the prior ARE YOU SURE? •
section, the value for ET (error track) will tell you how many files were scratched. For
exampl~, if your diskette contains program files named "TEST", "TRAIN", before Basic obeys a Scratch command . If you are sure, simply press Y and RETURN . If
"TRUCK", and "TAIL"; you may scratch all four, along with any other files beginning not, press RETURN alone or type anr other answer, and the command will be cancelled.
with the letter ''T'', by using the command: The number of files that were scratched will be automatically displayed . For exam-
ple, if your diskette contains program files named "TEST'', "TRAIN", " TRUCK" , and
PRINT#l5, "SO:T*" "TAIL", you may scratch all four, along with any other files beginning with the letter
"T", by using the command:
Then , to prove they are gone, you can type:
SCRATCH "T*"
GOSUB 59990
and if the four listed were the only files beginning with " T" , you will see:
to call the error checking subroutine given earlier in this chapter, and ii the four listed
were the only files beginning with "T", you will see: 01,FILES SCRATCHED,04 ,00
The "04" tells you 4 files were scratched. SCRATCH ·(FOR ADVANCED USERS)
Scratch is a powerful command, and should be used with caution, to be sure you only
ERASING OLD PROGRAMS: BASIC 3.5 delete the files you really want erased . When using it with a pattern , we suggest you first
use the same pattern in a Directory command, to be sure exactly which files will be
The Scratch command allows you to erase unwanted programs and files from your deleted . That way you'll have no unpleasant surprises when you u·se the same pattern in
diskettes, and free up the space they occupied for use by other files and programs. It can the Scratch command.
be used to erase either a single file, or several files at once via pattern-matching (described
at the end of Chapter 3). Recovering from a Scratch
If you accidentally Scratch a file you shouldn't have, there is still a chance of saving
FORMAT FOR THE SCRATCH COMMAND: it. Like Basic ' s New command, Scratch doesn't really wipe out a file itself; it merely
clears the pointers to it in the diskette directory . If you immediately set the diskette aside
SCRATCH "pattern" ,Ddrive # ,Uunit # and protect it with a write-protect notch , to be sure no one adds any files to the diskette , a
skilled user in a nearby Commodore user group may be able to recover your file for you . It
Will help if you can remember what kind of file it was you scratched (program, sequential,
etc.), since that information cannot be directly recovered from what is left of the file .
32 33
More about Splats
EXAMPLES:
One other warning-never scratch a splat file. These are files that show up in a
directory listing with an asterisk (*)just before the file type for an entry . The asterisk (or
Just before saving a new copy of a ''calendar'' program, you might type:
splat) means that file was never properly closed, and thus there is no valid chain of sector
links for the Scratch command to follow in erasing the file.
PRINT# 15,' 'RO:CALENDAR/BACKUP =CALENDAR' '
If you Scratch such a file, odds are you will improperly free up sectors that are still
needed by other programs, and cause permanent damage to those other programs later
Or to move a program called "BOOT", currently the first program on a diskette to
when you add more files to the diskette . If you find a ·splat file, or if you discover too late
someplace else in the directory, you might type:
that you have scratched such a file, immediately validate the diskette using the Validate
command described later in this chapter. If you have added any files to the diskette since
PRINT# 15,' ' RO:TEMP =BOOT''
scratching the splat file, it is best to immediately copy the entire diskette onto another
fresh diskette, but do this with a copy .program rather than with a backup program .
followed by a Copy command (described later), which turns "TEMP" into a new copy of
Otherwise, the same problem will be recreated on the new diskette. When the new copy is
"BOOT'', and finishing with a Scratch command to get rid of the original copy of
done , compare the number of blocks free in its directory to the number free on the original
·•BOOT", since renamed to "TEMP" by the command above.
diskette . If the numbers match, no damage has been done. If not, very likely at least one
file on the diskette has been corrupted, and all should be immediately checked.
RENAMING PROGRAMS: BASIC 3.5
Locked Files
The Rename command allows you to alter the name of a program or other file in the
Very occasionally, a diskette will contain a locked file; that is one which cannot be
diskette directory. Since only the directory is affected , Rename works very quickly .
erased with the Scratch command. Such files may be recognized by the "<" character
which immediately follows the file type in their directory entry. If you wish to erase a
FORMAT FOR RENAME COMMAND:
locked file, you will have to use a disk monitor to clear bit 6 of the file-type byte in the
directory entry on the diskette . Conversely , to lock a file, you would set bit 6 of the same
RENAME " old name" TO "new name" ,Ddrive #,Udevice #
byte. For more information on how such tricks are done, see Chapter 9 and Appendices D
and E.
where "new name" is the name you want the file to have, and " old name" is the name it
has now . "new name" may be any string expression that evaluates to a valid file name ,
RENAMING PROGRAMS: BASIC 2
up to 16 characters in length . If "D" is left out, drive 0 is assumed . If " U" is absent,
device 8 is assumed. One caution-be sure the file you are renaming has been properly
The Rename command allows you to alter the name of a program or other file in the
closed before you rename it.
diskette directory . Since only the directory is affected, Rename works very quickly.
EXAMPLES :
FORMAT FOR RENAME COMMAND:
Just before saving a new copy of a ''calendar'' program , you might type:
PRINT#l5 ," RENAMEO:new name=old name"
RENAME ''CALENDAR'' TO ' 'CALENDAR/BACKUP''
or it may be abbreviated as:
Or to ·move a program called "BOOT", currently the first program on a diskette to
PRINT#l5 ,"RO:new name= old name" someplace else in the directory , you might type :
where "new name" is the name you want the file to have, and "old name" is the name it RENAME "BOOT" TO "TEMP"
has now . " new name " may be any valid file name , up to 16 characters in length. It is
assumed you have already opened file 15 to the command channel. followed by a Copy command (described later), which turns " TEMP" into a new copy of
One caution-be sure the file you are rem.ming has been properly closed before you ''BOOT", and finishing with a Scratch command to get rid of the original copy of
rename it. "BOOT", since renamed to " TEMP" by the command above .
34 35
RENAMING AND SCRATCIDNG TROUBLESOME FILES COPYING PROGRAMS: BASIC 2
(ADVANCED USERS)
The Copy command allows you to make a spare copy of any program or file on a
Eventually, you may run across a file which has a crazy filename, such as a comma diskette. However, on a single drive like the 154 I, the copy must be on the same diskette ,
by itself( "," ) or one that includes a SHIFfed SPACE. Or perhaps you will find one that which means it must be given a different name from the file copied . It's also used to
includes nonprinting characters . Any of these can be troublesome. Comma files , for concatenate up to four sequential data files (combining them by linking one to another,
instance, are an exception to the rule that no two files can have the same name. Since it end to end in a chain) . Files are linked in the order in which they appear in the command .
shouldn ' t be possible to make a file whose name is only a comma, the disk never expects The source files and other files on the diskette are not changed . Files must be closed
you to do it again . before they are copied or concatenated'.
Files with a SHIFT-SPACE in their name can also be troublesome, because the disk
interprets the shifted SPACE as signalling the end of the file name, and prints whatever FORMAT FOR THE COPY COMMAND
follows after the quotation mark that marks the end of a name in the directory . This
technique can also be useful , allowing you to have a long file name, but also make the PRINT#l5, " COPYdrive # :new file=drive # :old file "
disk recognize a small part of it as being the same as the whole thing without using
pattern-matching characters . EXAMPLES :
In any case, if you have a troublesome filename, you can use the Chr$() function to PRINT#IS, " COPYO:BACKUP=ORIGINAL"
specify troublesome characters without typing them directly . This may allow you to build
them into a Rename command . If this fails, you may also use the pattern-matching or abbreviated as
characters in a Scratch command . This gives you a way to specify the name without using
the troublesome characters at all , but also means loss of your file . PRINT#IS, " Cdrive #:new file=drive # :old file"
For example , if you have managed to create a file named " "MOYIES", with an
extra quotation mark at tile front of the file name, you can rename it to " MOYIES" by PRINT# IS , " CO:BACKUP= ORIGIN~L "
using the Chr$() equivalent of a quotation mark in the Rename command:
where "drive#" is the drive number (0 on the 1541,) "new file" is the copy, and " old
BASIC 2 FORMAT: file" is the original.
PRINT#l5 ," RO:MOYIES = " +CHR$(34)+ "MOYIES" FORMAT FOR THE CONCATENATE OPTION
BASIC 3.5 FORMAT: PRINT# 15, "Cdrive # :new file= drive # :file l ,drive#:file 2,drive #:file 3,drive
REN AME (CHR$(34) + " MOYIES " ) TO " MOYIES " #:file 4"
The CHR$(34) forces a quotation mark into the command string ':Yithout upsetting Basic. where "drive #" is the drive number for each file . Since it is always 0 on the 1541, the
The procedure for a file name that includes a SHIFT-SPACE is similar, but uses drive number is often omitted .
CHR$(160) .
In cases where even this doesn 't work, for example if your diskette contains a comma EXAMPLES :
file, (one named "," )you can get rid of it this way :
After renaming a file named "BOOT" to "TEMP" in the last section's example, we
BASIC 2 FORMAT: BASIC 3.5 FORMAT: · can use the Copy command to make a spare copy of the program elsewhere on the
diskette, under the original name:
PRINT#l5 ," SO:?" SCRATCH " ?'"
PRINT# 15, "CO: BOOT= TEMP"
Depending on the exact problem, you may have to be very creative in choosing pattem-
matching characters that will affect only the desired file, and may have to rename other After creating several small s~quential files that each fit easily in memory along with
files first to keep them from being scratched too. a program we are using, we can use the concatenate option to combine them in a 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 will be as big as the sum of the sizes of the files in it.)
36 37
NOTE: Dual drives make fuller use of this command, copying programs from one diskette
clo sed file (splat file), indicated by an asterisk(*) next to its ·file bel
type in the directory, that
to another in a single disk unit. To do that on the 1541, refer to Appendix E to find the . kette needs to be validated. ln fact, but for the one exception ow, It· 1s
· a good 1"dea to
programs that you need. disrdate diskettes whenever you are the least bit · concemed a bo ut their · mtegn
· "ty.
va The exception is diskettes containing Direct Access files, as described in Chapt~r 7 ·
1
COPYING PROGRAMS: BASIC 3.5 , 6 t direct access (random) files do not allocate their sectors in a way the Validate
JVIOS • I .
ornmand can recognize. Thus, using Validate on such a diskette may resu t m un-
The Copy command allows you to make a spare copy of any program or file on a :nocating all direct access files, with loss of all their c?ntents wh~n other files. a:e ad~ed.
diskette . However, on a single drive like the 1541, the copy must be on the same diskette , Unless specifically instructed otherwise, never use Validate on a diskette contammg direct
which means it must be given a different name from the file copied. The source file and access files. (Note: these are not the same as the relative files described in Chapter 6.
other files on the diskette are not changed. Files .bust be closed before they are copied. Validate may be used on relative files without difficulty.)
Although the 1541 supports a Concatenate option, Basic 3.5 doesn't have a special
command for it. The Basic 2 syntax from the previous page may be used instead. FORMAT FOR THE VALIDATE COMMAND
FORMAT FOR THE COPY COMMAND PRINT# 15,' 'V ALIDA TEO''
where "D" is the drive number (always 0 on the 1541,) "new file" is the copy, "old PRINT#l5,"VO"
file" is the original, and "U" is the device number. If omitted, the drive number defaults
to 0 and the device number (unit) to 8. where "O" is the drive number (always 0 on the 1541.) As usual, it is assumed file 15 has
been opened to the command channel on the 1541.
EXAMPLES:
EXAMPLE:
After renaming a file named "BOOT" to 'TEMP" in the last section's example, we
can use the Copy command to make a spare copy of the program elsewhere on the PRINT#l5 ,"VO'
diskette, under the original name:
VALIDATING THE DISKETTE: BASIC 3.5
COPY "TEMP" TO "BOOT"
The Collect command in Basic 3.5 is the same as the Validate command in Basic 2.
To copy a file on a second disk drive, we would use: It recalculates the Block Availability Map (BAM) of the current diskette, allocating only
those sectors still being used by valid, properly-closed files and programs. All other
COPY "ORIGINAL" TO "BACKUP'',U9 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
NOTE: Dual drives make fuller use of this command, copying programs from one diskette either the power or the danger of the Collect command. Its power is in restoring to good
to another in a single disk unit. To do that on the 1541, refer to Appendix E to find the health many diskettes whose directories or block availability maps have become muddled.
programs that you need . Any time the blocks used by the files on a diskette plus the block~ shown as free don't add
up to the 664 available on a fresh diskette, Collect is needed (with one exception below.)
VALIDATING THE DISKETTE: BASIC 2 Similarly , any time a diskette contains an improperly-closed file (splat file), indicated by
an asterisk (*) next to its file type in the directory, that diskette needs to be collected. In
The Validate command recalculates the Block Availability Map (BAM) of the fact, but for the one exception below, it is a good idea to collect diskettes whenever you
current diskette, allocating only those sectors still being used by valid, properly-closed are the least bit concerned about their integrity . Just note the number of blocks free in the
files and programs. All other sectors (blocks) are left unallocated and free for re-use, and diskette's directory before and after using Collect, and ifthe totals differ, there was indeed
all improperly-closed files are automatically Scratched. However, this bare description of a problem, and the diskette should probably be copied onto a fresh diskette file by file,
its workings doesn't indicate either the power or the danger of the Validate command. Its using the Copy command described in the previous section, rather than usiqg a backup
wer is in restoring to g,)()d health many diskettes whose directories or block availability command or program . .
maps have become muddled . Any time the blocks used by the files on a diskette plus the The exception is diskettes containing Direct Access files, as described in Chapter 7 ·
blocks shown as free don't add up to the 664 available on a fresh diskette, Validate is Most direct access (random) files do not allocate their sectors in a way Collect can
needed, with one exception below. Similarly, any time a diskette contains an improperly- recognize. Thus, collecting such a diskette may result in un-allocating all direct access
38 39
One use for Initialize is to keep a cleaning diskette spinning , if you choos_e _to use
files , with loss of all their contents when other files are added . Unless specifically (There is no need to use such kits on any regular basis und~r normal con~1t1ons of
instructed otherwise, never collect a diskette containing direct access files. (Note: these o~~liness and care.) Nonetheless, if you are using such a kit, the followmg short
are not the same as the relative files described in Chapter 6. Collect may be used on c e will keep the diskette spinning long enough for your need:
relative files without difficulty .) program
tO OPEN 15 ,8, 15
FORMAT FOR THE COLLECT COMMAND
20 FOR I= I TO 99
30: PRINT#l5 ," IO"
COLLECT Ddrive # , Udevice #
40NEXT
SO CLOSE 15
where "D" is the drive number (always 0 on the 1541 ,) and "U" the device number. As
usual , if omitted they default to drive 0 and device 8 respectively . uses an Initialize loop to keep the drive motor on for about 20 seconds .
11
EXAMPLE:
COLLECT DO
INITIALIZING
One command that should not often be needed on the 1541, but is still of occasional
value is Initialize. 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 when a diskette is changed.)!'
The result of an Initialize, whether forced by a command, or done automatically by
the disk, is a re-reading of the current diskette's BAM (Block Availability Map) into a
disk buffer. This information must, of course, always be correct in order for the disk to
store new files properly . However, since the chore is handled automatically, the only time
you'd need to use the command is if something happened to maJCe the information in the
drive buffers umeliable. Even so, you may use the command for reassurance, as often as
you like, so long as you close all your files except for the command channel first.
where the command channel is assumed to be opened by file 15, and "drive #" is 0 on
the 1541.
41
40
CHAPTERS Before we study the format of the Open statement, let's review some of the possible
SEQUENTIAL DATA FILES devices in a Commodore computer system:
where:
"file #" is an integer (whole number) between I and· 255. If the file number is
OPENING A FILE greater than 127, a line-feed character is inserted after each carriage return in the fil.e
opened. Though this may be helpful in printer files, it will cause severe problems in disk
One of the most powerful tools in Commodore Bllsic is the Open statement. With it , files, and is to be avoided at all costs. Do not open a disk file with a file number greater
you may send almost any data almo~t anywhere, much like a telephone switchboard that than 127. After the file is open, all other file commands will refer to it by the number
can connect any caller to any .destination. As you might expect, a command that can do given here . Only one file can use any given file number at a time .
this much is fairly complex. You have already used Open statements regularly in some of "device #" is the number, or primary address, of the device to be used . This
your diskette housekeeping commands. number is an integer in the range 0-31, and is normally 8 on the 1541.
42 43
"channel #" is a secondary address, giving further instructions to the selected
Of course, this erases all our old phone numbers, so make sure that any information that
device about how further commands are to be obeyed . In disk files, the channel number
1118y be deleted is of no importance . After writing our phone file, we remove our di skette
selects a particular channel along which communications for this file can take place. The
and tum off the system . Later, to recall the data in the file, we would reopen it with
possible range of disk chan!'el numbers is 0-15, but 0 is reserved for program Loads , I for
something like
program Saves, and 15 for the disk command channel. Also be sure that no two disk files
have the same channel number unless they wiIJ never be open at the same time. (One way
OPEN 8,8 ,8, " 0:PHONES,S ,R"
to do this is to make the channel number for each .file the same as its file pumber.)
"drive#" is the drive number, always 0 on the 1541. Do not omit it, or you will
It doesn 't matter whether the file and channel numbers match the ones we used before , but
only be able to use two channels at the same time instead of the normal maximum of three .
the file name does have to match. However. it is possible to use an abbreviation form of
If any pre-existing file of the same name is to be replaced, precede the drive number with
the file name, if there are no other files that would have the same abbreviation:
the "at" sign(@) to request Open-with-replace.
"file name" is the file name, maximum length 16 characters . Pattern matching OPEN 10,8,6, "O:PH* ,S,R"
characters are allowed in the name when accessing existing files , but not when creating
new ones. If we have too many phone numbers , they might not fit in one file . In that case, we
"file type" is the file type desired: S=sequential, P=program, U=user, and
might use several similar file names, and let a program choose the correct file .
L =length of a relative file .
"direction" is the type of access desired . There are three possibilities: R =read, 100 INPUT "WHICH PHONE FILE ( l-3)" ;PH
W =write , and M =modify . When creating a file , use "W" to write the data to diskette . 110 IF PH <> I AND PH <>2 AND PH <>3 THEN 100
When viewing a completed file, use " R" to read the data from diskette. Only use the 120 OPEN 4 ,8,2," PHONE " + STR$(PH)+ ",S,R"
"M" (modify) option as a last ditch way of reading back data from an improperly-closed
(Splat) file . (If you try this, check every byte as it is read to be sure the data is still valid ,
You can omit the drive number on an Open command to read a file . Doing so allows those
as such files always include some erroneous data, and have no proper end.) with dual drives to search both diskettes for the file .
"file type" and "dir.e ction" don't have to be abbreviated . They can be spelled out
in full for clarity in printed listings .
"file#", "device#" and "channel#" must be valid numeric constants , variables
or expressions . The rest of the command mus~ be a valid string literal , variable or Note: Basic 2 and Basic 3.5 use the same file handling commands and the same
expression . direct access commands (chapters 7-8) . Unless otherwise noted , you may use the
same commands for both throughout the remainder of this book.
The maximum number of files that may be open simultaneously is 10, including all
files to all devices . The maximum number of sequential disk files that can be open at once
is 3 (or 2 if you neglect to include the drive number in your Open statement), plus the
command channel .
ADDING TO A SEQUENTIAL FILE
On Commodore's PET and CBM models, an Append command allows you to reopen
EXAMPLES OF OPENING SEQUENTIAL FILES :
an existing sequential file and add more information to the end of it. The same thing can
be done another way on the 1541. In place of the " type" and "direction" parameters in
To create a sequential file of phone numbers , you could use:
your Open statement, substitute ",A" for Append . This will reopen your file, and
position the disk head at the end of the existing data in your file, ready to add to it.
OPEN 2,8 ,2, "O:PHONES,SEQUENTIAL, WRITE"
FORMAT FOR THE APPEND OPTION
or save yourself some typing with :
OPEN file # ,device # ,channel #,"drive #:file name,A"
OPEN 2,8,2,"0:PHONES,S,W"
Where. everything is as on the previous page except for the ending "A" replacing the
On the off-chance we've already got a "PHONES" file on our diskette, we can avoid a
"type" and "direction" parameters .
" FILE EXISTS" error message by doing an @ OPEN
44 45
EXAMPLE: "°here "file#" is the same file number given in the desired file's current Open statement.
purin& any given access of a particular file, the file number must remain constant because
If you are writing a grading program, it wou.ld be convenient to simply tack on each . serves as a shorthand way of relating all other file-handling commands back to the
1
student's new grades to the end o( their existing grade files . To add data to the "JOHN ~orrect Open statement. Given a file number, the computer can look up everything else
PAUL JONES" file, we could type a!JOUt a file that matters.
The "data list" is the same as for a Print statement - a list of constants, variables
OPEN 1,8,3, "O:JOHN PAUL JONES.A" andfor expressions, including numbers, strings or both. However, it is strongly recom-
mended that each Print# statement to disk include only one data item. If you wish to
In this case, DOS will allocate at least one more sector (block) to the file the first iflClude more items, they must be separated by a carriage return character, not a comma.
time you append to it, even if you only add one character of information. You may also Semicolons are permitted, but not recorded in the file, and do not result in any added
notice that using the Collect or Validate command didn't correct the file size. On-the other spaces in the file. Use them to separate items in the list that might otherwise be confused,
hand, your data is quite safe, and if the wasted space becomes a problem, you can easily such as a string variable immediately following a numeric variable.
-correct it by copying the file to the same diskette or a different one, and scratching the
original file. Here's a sequence of commands that will copy such files to the original
diskette under the :>riginal name, for ease of continued use:
Note: Do not leave a space between PRINT and #, and do not abbreviate the
BASIC 2: command as?#. The correct abbreviation for Print# is pR.
PRINT#l5,"RO:TEMP=JOHN PAUL JONES"
PRINT#l5,"CO:JOHN PAUL JONES=TEMP"
PRINT# 15,' 'SO: TEMP''
EXAMPLES:
BASIC 3.5:
RENAME "JOHN PAUL JONES" TO "TEMP" To record a few grades for John Paul Jones, using a sequential disk file #1 previously
COPY "TEMP" TO "JOHN PAUL JONES" opened for writing, we could use:
SCRATCH "TEMP"
200 FOR CLASS= 1 TO COURSES
If you are using Basic 2, be sure to open file 15 to the command channel beforehand (i.e ., 210: PRINT#l,GRADE.$(CLASS)
with OPEN 15,8,15) and close it afterwards (i.e. , with CLOSE 15). 220 NEXT CLASS
320 GOSUB 59990:REM CHECK FOR DISK ERRORS
WRITING FILE DATA: USING PRINT#
After a sequential file has been opened to write (with a type and direction of (assuming your program includes an error check subroutine like the one in the last
",S,W"), we use the Print# command to send data to it for storage on diskette. If you are chapter).
familiar with Basic's Print statement, you will find Print# works exactly the same way , In using Print# there is an exception to the requirement to check for disk
except that the list of items following the command word is sent to a particular file , errors after every file-handling statement. When using Print#, a single check after
instead of automatically appearing on the screen. Even the formatting options (punctua- an entire set of data has been written will still detect the error, so long as the check
tion and such) work in much the same way as in Print statements. This means you have to is made before any other file-handling statement or disk command is used. You
be sure the items sent make sense to the particular file and device used. may be familiar with Print statements in which several items follow each other:
For instance, a comma between variables in a Print statement acts as a separator in
screen displays, making each successive item appear in the next preset display field 400 PRINT NAME$,STREET$,CITY$
(typically at the next column whose number is evenly divisible by 10). If the same comma
is included between variables going lo a disk file, it will again act as a separator, again To get those same variables onto sequential disk file number 5 instead of the screen, the
inserting extra spaces into the data. This time, however, it is inappropriate, as the extra best approach would be to use three separate Print# statements, as follows:
spaces are simply wasted on the diskette, and may create more problems when reading the
file bl!ck into the computer. Therefore, you are urged to follow the following format 400 PRINT#5,NAME$
precisely when sending data to a disk file . 410 PRINT#5 ,STREET$
420 PRINT#5,CITY$
FORMAT FOR THE PRINT# STATEMENT
PRINT#file #,data list
46 47
However, if you need to combine them , here is a safe way to do it: 0 close every file you even think might be open before ending a program . If for
~~an:ple, we always gave our files numbers between I and 10, we could close them all
400 PRINT#5,NAME$;CHR$(13) ;STREET$;CHR$(13);CITY$ with
9950 FOR I= I TO 10
CHR$(13) is the carriage return character, and has the same effect as putting the print
9960 CLOSE I
items in separate lines . lf you do this often , some space and time may be saved by
9970 GOSUB 59990:REM CHECK FOR DISK ERRORS
previously defining a variable as equal to CHR$(13):
9980 NEXT I
10 CR$=CHR$(13) . .. 400 PRINT#5 ,NAME$;CR$;STREET$;CR$;CITY$
(assuming your program includes an error check subroutine like the one in Chapter 4)
The basic idea is that a proper sequential dis)c file write, if redirected to the screen,
READING FILE DATA: USING INPUT#
will display only one data item per line, with each succeeding item on the next line.
Once information has been written properly to a diskette file, it may be read back into
CLOSING A FILE WHEN YOU ARE DONE USING IT the computer with an Input# statement. Just as the Print# statement is much like the Print
statement, Input# is nearly identical to Input, except that the list of items following the
After you finish using a data file , it is extremely important that you Close it. During command word comes from a particular file instead of the keyboard . Both statements are
the process of writing a file, data is accumulated in a memory buffer, and only written out subject to· the same Jimitations--halting input after a comma .or colon, not a~ceptin~ data
lo the physical cassette or diskette when the buffer fills . items too large to fit in Basic 's Input buffer, and not acceptmg non-numenc data mto a
Working this way , there is almost always a small amount of data in the buffer that numeric variable.
has not been written to diskette or cassette yet, and which would simply be Jost if the
computer system were turned off. Similarly , there are diskette housekeeping matters , such FORMAT FOR THE INPUT# STATEMENT
as updating the BAM (Block Availability Map) of sectors used by the current file , which
are not performed during the ordinary course of writing a file . This is the reason for PRINT#file # ,variable list
having a Close statement. When we know we are done with a file, the Close statement
will write the rest of the data buffer out to cassette or diskette, update the BAM , and where "file#" is the same file number given in the desired file's current Open statement,
complete the file's entry in the directory . Always Close a data file when you are done and "variable list" is one or more valid Basic variable names . If more than one data
using it! Failure to do so may cause loss of the entire file! element is to be input by a particular Input# statement, each variable name must be
However, do not clo~e the disk command channel until all other files have been separated from others by a comma.
Closed . The command channel (described in the last chapter) , when used, should be the
first file Opened, and the last file Closed in any program . Otherwise, remaining files may EXAMPLES :
be closed automatically . As also described there, this may be used to advantage if a
program halts on an error while disk files are open. To read back in the grades written with the Print# example, use:
48 49
but many programs cheat on safety a bit anel UM; quotation mark, in either an Input or Input# statement, all other characters except a
carriage return or another quotation mark are accepted as part of the current data element.
800 INPUT#5,NAME$,STREET$,CITY$
810 GOSUB 59990:REM CHECK FOR DISK ERRORS EXAMPLES:
This is done primarily when top speed in the program is essential, and there is little or no To force a quotation mark into a data element going to a file, append a CHR$(34) to
risk of reading improper data from the file . the start of the data element. For example:
Troublesome Characters or
After you begin using data files regularly, you may encounter two Basic error
messages more or less frequently . They are "STRING TOO LONG ERROR" and "FILE PRINT#2,CHR$(34);''STRASMA, JIM''
DATA ERROR" . Both are likely to halt your program at an Input# statement, but may
also have been caused by errors in a Print# statement when the file was written. If you do this often, some space and time may be saved by previously defining a variable
as equal to·CHR$(34) as we did earlier with CHR$(13):
"STRING TOO LONG" ERRORS
A Basic string may be up to 255 characters long, although the longest string you can 20 QT$= CHR$(34)
enter via a single Input statement is just under 2 lines of text (4 on the VIC 20) . This lower
limitation is due to the 88 character size of the Input buffer in Commodore's serial bus 400 PRINT#5 ,QT$,+ NAME$
computers. The same limit applies to Input# statements. If a single data element (string or
number) being read from a disk file into an Input# statement contains more than 87 In each case, the added quotation mark will be stripped out of the data by the Input or
characters, Basic will halt with a "STRING TOO LONG ERROR". To prevent this Input# statement, but the comma or colon will remain safely part of the data.
error, be sure to limit each string to under 88 characters, and separate all file data items
with carriage returns (See the next section for a cure once the error has occurred.) NUMERIC DATA STORAGE ON DISKETTE
"FILE DATA" ERRORS Inside the computer, the space occupied by a numeric variable depends only on its
The other error message "FILE DATA ERROR" is caused by attempting to read a type. Simple numeric variables use 7 bytes (character locations) of memory. Real array
non-numeric character into a numeric variable. To a computer, a number is the characters variables use 5 byte§ per array element, and integer array elements use 2 bytes- each. In
0 through 9, the"+" ana " - " signs, the decimal point(.), the SPACE character, and contrast, when a numeric variable or any type is written to a file, the space it occupies
the letter "E" used in scientific notation. If any other character appears in an Input# to a depends entirely on its length, not its type.
numeric variable, "FILE DATA ERROR" will be displayed and the program will halt. Numeric data is written to a file in the form of a string, as if the Str$() function had
The usual causes of this ,error are a mismatch between the order in which variables are been performed on it. The first character will be a blank space if the number is positive,
written to and read from a file, a missing carriage return .;.,,ithin a Print# statement that and a minus sign ( - ) if the number is negative. Then comes the number, digit by digit.
writes more than one data item, or a data item that includes either a comma or a colon The last character is a cursor right character.
without a preceding quotation mark . Once a file data error has occurred, you should This format allows the disk data to be read back into a string or numeric variable
correct it by reading the data item into a string variable, and then converting it back to a later. It is, however, somewhat wasteful of disk space, and it can be difficult to anticipate
number with the Basic Val() statement after removing non-numeric characters with the the space required by numbers of unknown length . For this reason, some programs
string functions described in your computer users manual. convert all numeric variables into strings before writing them to diskette, and use string
functions to remove any unneeded characters in advance. Doing so still allows those data
COMMAS (,) AND COLONS (:) elements to be read back into a numeric variable by Input# later, although file data errors
As suggested before, commas and colons can cause trouble in a file, because they ~ay be avoided by reading all data in as strings. and converting to numbers after the
delimit (end) the data element in which they appear and cause any remaining characters in Information is inside the computer.
the data element to be read into the next Input# variable. (They have the same effect in an For example, "N$ = MID$(STR$(N),2)" will convert a positive number N into a
Input statement, causing the common "EXTRA IGNORED" error message.) However, String N$ without the usual leading space for its numeric sign . Then instead of writing
sometimes we really need a comma or colon within a data element, such as a name written PRINT#5,N , you would use PRINT#5,N$ .
as "Last, First". The cure is to precede such data elements with a quotation mark. After a
50 51
Get# may be especially useful in recovering damaged files, or files with unknown
READING FlLE DATA: USING GET#
contents . The Ba~ic reserved variable ST (the file STatus variable) can be used to indicate
The Get# statement retrieves data from the disk drive , one character at a time . Like wben all of a properly-closed file has been read .
the similar keyboard Get statement in Basic, it only accepts a single character into a
specified variable . However, unlike the Get statement, it doesn 't just fall through to the 500 GET#2,S$
next statement if there is no data to be gotten . The primary use of Get# is to retrieve from 510 SU=ST:REM REMEMBER FILE STATUS
diskette any data that cannot be read into an Input# statement, either because it is too long 520 PRINTS$ ; ,
530 IF SU= 0 THEN 500:REM IF THERE' S MORE TO BE REA L
to fit in the input buffer or because it includes troublesome characters .
540 IF SU <> 64 THEN PRINT " STATUS ERROR: ST = " ;SU
FORMAT FOR THE GET# STATEMENT:
copying ST into SU is often an unneccessary precaution, but must be done if any other
file-handling statement appears between the one which read from the file and the one that
GET#file# , variable list
1oops back to read again . For example , it would be required if line 520 was changed to
where "file#" is the same file number given in the desired file's current Open statement,
and "variable list" is one or more valid Basic variable names. If more than one data 520 PRINT# l ,S$ ;
element is to be input by a particular Get# statement, each variable name must be
Otherwise, the file status checked in line 530 would be that of the write file, not the read
separated from others by a comma .
In practice , you will almost never see a Get or Get# statement containing more than file.
one variable name . If more than one character is needed, a loop is used ~ather than
additional variables . Also as in the Input# statement, it is safer to use string variables
when the file to be read might contain a non-numeric character. POSSIBLE VALUES OF THE FILE STATUS VARIABLE ''ST' ',
Data in a Get# statement comes in byte by byte, including such normally invisible AND l'HEIR MEANINGS
characters as the Carriage Return , and the various cursor controls . All but one will be read
properly . The exception is CHR$(0) , the ASCII Null character. It is different from an IF ST= THEN
empty string(oneofthe form A$=" "),even though empty strings are often referred to as 0 All is OK
null strings . Unfortunately , in a Get# statement , CHR$(0) is converted into an empty I Receiving device was not available (time out on talker)
string . The cure is to test for an empty string after a Get#, and replace any that are fo und 2 Transmitting device was not available (time out on listener)
with CHR$(0) instead . The first example below illustrates the method . 4 Cassette data file block was too short
8 Cassette data file block was too long
EXAMPLES : 16 Unrecoverable read error from cassette , verify error
32 Cassette checksum error--0ne or more faulty characters were read
To read a file that may contain a CHR$(0) , such as a machine language program file , 64 End of file reached (EOI detected)
we could correct any CHR$(0) bytes with 128 Device not present, or end of tape mark found on cassette
If an overlong string has managed to be recorded in a file , it may be safely read back
into the computer with Get#, using a loop such as this
The limit for such a technique is 255 characters. It will ignore CHR$(0) , but that may be
an advantage in building a text string .
53
52
CHAPTER6
DEMONSTRATION OF SEQUENTIAL FILES RELATIVE DATA FILES
Use the following program for your first experiments with sequential files . TffE VALUE OF RELATIVE ACCESS
Comments have been added to help you better understand it.
Sequential files are very useful when you 're just working with a continuous stream of
150 CR$=CHR$_(13) Make a carriage return variable data- i.e., information that can be read or written all at once. However, sequential files
1600PEN 15,8,15 are not useful or desirable in some situations. For example, after writing a large list of
170 PRINT CHR$(147):REM CLEAR mail labels, you wouldn't want to have to re-read the entire list each time you need a
SCREEN person's record . Instead, you need some kind of random access, a way to get to a
190 PRINT"** WRITE A FILE**" particular label in your file without having to read through all those preceding it first.
210 PRINT As an example, compare a record turntable with a cassette recorder. You have to
220 OPEN 2,8,2,"@0:SEQ FILE,S,W" Open demo file with replace listen to a cassette from beginning to end, but a turntable needle can be picked up at any
230 GOSUB 500 Check for disk errors time, and instantly moved to any spot on the record . Your disk drive works like a turntable
240 PRINT"ENTER A WORD, in that respect. In this chapter we will learn about a type of file that reflects this flexibility.
THEN A NUMBER'' Actually , two different types of random access files may be used on Commodore
250 PRINT"OR 'END,O' TO STOP" disk drives: relative files and random files. Relative files are much more convenient for
260 PRINT most data handling operations, but true random access file commands are also available to
270 INPUT A$,B Accept a string & number advanced users, and will be discussed in the next chapter.
from keyboard
280 PRINT#2,A$;CR$;B Write them to the disk file FILES, RECORDS, AND FIELDS
290 GOSUB 500
300 IF A$<>"END" THEN 270 Until finished When learning about sequential files, we did not worry about the organization of data
310 PRINT within a file, so long as the variables used to write the file matched up properly with those
320 CLOSE 2 Tidy up which read it back into the computer. But in order for relative access to work, we need a
340 PRINT"** READ SAME FILE more structured and predictable environment for our data.
BACK**" The structure we will use is similar to that used in the traditional filing cabinet. In a
360 PRINT traditional office, all customer records might be kept in a single file cabinet. Within this
370 OPEN 2,8,2, "O:SEQ FILE,S,R" Reopen same file for reading file, each customer has a personal record in a file folder with their name on it, that
380 GOSUB 500 contains everything the office knows about that person . Likewise, within each file folder,
390 INPUT#2,A$,B Read next string & number from file there may be many small slips of paper, each containing one bit of information about that
400 RS=ST Remember file status customer, such as a home phone number, ·or the date of the most recent purchase.
410 GOSUB 500 In a computerized office, the file cabinet is gone, but the concept of a file containing
420 PRINT A$,B Display file contents all the information about a group or topic remains. The file folders are gone too, but the
430 IF RS = 0 THEN 390 until done, notion of subdividing the file into individual records remains . The slips of paper within
440 IF RS<>64 THEN the personal records are gone too, replaced by subdivisions within the records, called
PRINT''STATUS= '';RS unless there's an error fields . Each field is large enough to hold one piece of information about one record in the
450CLOSE 2 Then quit file. Thus, within each file there are many records, and within each record there are
460 END typically many fields.
480 REM ** ERROR CHECK S/R ** A Basic 3.5-only version could A relative file takes care of organizing the records for you, numbering them from I to
500 INPUT#l5,EN,EM$ ,ET,ES replace line 500 with whatever, by ones, but the fields are up to you to organize. Each record will be of the
510 IF EN>O THEN PRINT 500 IF DS>O THEN PRINT same size, but the 1541 won't insist that they all be divided the same way . On the other
EN ,EMS.ET ,ES:STOP hand, they normally will all be subdivided the same way, and if it can be known in
DS$:STOP advance exactly where each field starts within each record, there are even fast ways to
520 RETURN and delete line 510 access a desired field within a record without reading through the other fields . As all of
this implies, access speed is a primary reason for putting information into a relative disk
file. Some well-written relative file programs are able to find and read the record of one
54 55
desired person out of a thousand in under 15 seconds, a feat no sequential file prograrn
could match.
Notes:
FILE LIMITS I. Do not precede the drive number with the "at" sign(@); there is no reason
to replace a relative file.
. One of the nicest aspects of relative files is that all this is done for you without you r 2. ,L , "+ CHR$(record length) is only required when a relative file is first
havmg to worry at all about exactly where on the diskette's surface a given record will be created, though it may used later, so long as the "record length" is the same as
stored, or whether it will fit properly within the ;current disk sector, or need to be extended when the file was first created . Since relative files may be read from or written to
onto. the next available sector. DOS takes care of all that for you . All you need to do is alternately and with equal ease, there is no need to specify Read or Write mode
specify how long each record is, in bytes, and how many records you will need. DOS wi ll when opening a relative file.
do the rest, and organize things in such a way that it can quickly find any record in the file 3. "file#", "device#" and "channel#" must be valid numeric constants,
as soon as it is given its record number (ordinal position within the file). ' variables or expressions. The rest of the command must be a valid string literal,
The only limit that will concern you, is that each record must be the same size, and variable or expression .
the record length you choose must be between 2 and 254 characters . Naturally the entire 4. Only 1 relative file can be open at a time on the 1541, although a sequential
file also has to fit on your diskette too, which means that the more records you need, the file and the command channel may also be open at the same time.
shorter each must be.
56
57
FORMAT FOR THE RECORD# COMMAND: 450 INPUT"RECORD # DESIRED";RE
460"IF RE<l OR RE>65535 THEN 450
PRINT#l5, "P" +CHR$ (channel #+96) + CHR$ (<record #)+CHR$ 470 RH= INT(RE/256)
(>record #) + CHR$ (offset) 480 RL = RE-256*RH
490 PRINT#l5, "P" +CHR$ (98) +CHR$ (RL) +CHR$ (RH)
where "channel #" is the channel number specified in the current Open statement for the
specified file, "<record#" is the low byte of the desired record number, expressed as a Assuming RH and RL are calculated as in the previous example, programs may 3lso use
two byte integer, ">record #" is the high byte of the desired record number, and an variables for the channel, record, and offset required:
optional "offset" vaiue, if present, is the byte within the record at which a followin g
Read or Write should begin. 570 INPUT "CHANNEL, RECORD, & OFFSET DESIRED";CH,RE,OF
To fully understand this command, we must understand how most integers are stored 630 PRINT#I5, "P"+CHR$(CH +96) +CHR$ (RL) +CHR$ (RH) +CHR$ (OF)
in computers based on the 6502 and related microprocessors . In the binary arithmetic used
by the microprocessor, it is possible to express any unsigned integer from 0-255 in a
single byte . It is also possible to store any unsigned integer from 0-65535 in 2 bytes, with
1 byte holding the part of the number that is evenly divisible by 256, and any remainder in
ANOTHER RECORD# COMMAND
the other byte. In machine language, such numbers are written backwards, with the low-
order byte (the remainder) first, followed by the high order byte . In assemhly language
Basic 4.0 on Commodore's PET and CBM models includes a Basic Record#
programs written with the Commodore Assembler. the low part of a two byte number is
command not found in any of the serial bus computers. However, some available
indicated by preceding its label with the less-than character(<) . Similarly. the high part
utility programs for these models include it. It serves the same function as the
of the number is indicated by greater-than (>).
Record# command explained above, but has a simplified syntax:
EXAMPLES:
To position the record pointer for file number 2 to record number 3, we could type: COMPLETING RELATIVE FILE CREATION
PRINT #15, "P" +CHR$ (98) +CHR$ (3) +CHR$ (0) Now that we have learned how to use both the Open and Record# commands, we are
almost ready to properly create a relative file. The only additional fact we need to know is
The CHR$(98) comes from adding the constant (96) to the desired channel number (2 ). that CHR$(255) is a special character in a relative file . It is the character used by the DOS
(96 + 2 = 98) Although the command appears to work even when 96 is not added to the to fill relative records as they are created, before a program fills them with other
channel number, the constant is no1 mally added to maintain compatibility with the way information. Thus, if we want to write the last record we expect to need in our file with
Record# works on Commodore's CBM and PET computers . dummy data that will not interfere with our later work, CHR$(255) is the obvious choice .
Since 3 is less than 256, the high byte of its binary representation is 0, and the entire Here is how it works in an actual program which you may copy for use i~ your own
value fits into the low byte. Since we want to read or write from the beginning of the relative file programs.
record, no offset value is needed.
Since these calculations quickly become tedious, most program~ arc written to do 1020 OPEN 15,8, 15 Open command channel
them for you . Here is an example of a program which inputs a record number and converts 1380 INPUT" ENTER RELATIVE FILE NAME";F1$ Select file parameters
it into the required low byte/high byte form: 1390 INPUT" ENTER MAX.# OF RECORDS";NR
1400 INPUT"ENTER RECORD LENGTH" ;RL
58 59
WRITING RELATIVE FILE DAT A
1410 OPEN 1,8,2, "O:"+FI$+" ,L,"+CHR$(RL) Begin to create desired file
1420 GOSUB 59990 Check for disk errors The commands used to read and write relative file data are the same Print#, Input#,
1430 RH= INT(NR/256) Calculate length values and Get# commands used in the preceding chapter on Sequential files . Each command is
1440 RL = NR-256*RH used as described there. However, some aspects of relative file access do differ from
1450 PRINT#l5, "P" +CHR$(96+ 2) + sequential file programming, and we will cover those differences here.
CHR$(RL) + CHR$(RH) Position to last record
number DESIGNING A KELA TlVE RECORD
1460 GOSUB 59990
1470 PRINT#l,CHR$(255); Send default character to it As stated earlier in this chapter, each relative record has a fixed length , including all
1480 GOSUB 59990 special characters. Within that fixed length, there are two popular ways to organize
1490 PRINT#l5 , "P" + CHR$(96+ 2) + Re-position for safety various individual fields of information . One is free-format, with individual fields varying
CHR$(RL) + CHR$(RH) ·in length from record to record, and each field separated from the next by a carriage return
1500 GOSUB 59990 character (each of which does take up I character space in the record) . The other approach
1510 CLOSE 1 Now the file can be safely is to use fixed-length fields, that may or may not be separated by carriage returns. If fixed
closed length fields are not all separated by carriage returns, you will either need to be sure a
1520 GOSUB 59990 carriage return is included within each 88 character portion of the record . If this is not
9980 CLOSE 15 And the command channel done, you will have to use the Get# command to read the record, at a significant cost in
closed speed .
9990 END Before we end the pro- Relative records of 88 or fewer characters, or final portions of records that are 88 or
gram fewer characters in length, need not end in a carriage return . Jhe 1541 is smart enough to
59980 REM CHECK DISK SUBROUTINE recognize the end of a relative record even without a finar carriage return. Though the
59990 INPUT#l5,EN,EM$,ET,ES saving of a single character isn't much, when multiplied by the number of records on a
60000 IF EN> I AND EN<>50 THEN PRINT diskette, the savings could be significant.
EN ,EM$,ET ,ES:STOP Ignore "RECORD NOT Since each relative record must be written by a single Print# statement, the recom-
PRESENT'' mended approach is to build a copy of the current record in memory before writing it to
60010 RETURN disk . It can be collected into a single string variable with the help of Basic's many string-
handling functions, and then all written out at once from that variable .
Two lines require additional explanatiop. When line 1470 executes, the disk drive will Here is an example. If we are writing a 4-line mail label, consisting of 4 fields named
operate for up to ten or more minutes, creating all the records in the file, up to the "NAME' ', "STREET" , "CITY & STATE", and "ZIP CODE", and have a total record
maximum record number you selected in line 1390. This is normal, and only needs to be size of 87 characters, we can organize it in either of two ways:
done once. During the process you may hear the drive motor turning and an occasional
slight click as the head steps from track to track, everything is probably just fine . Second , WITH FIXED LENGTH FIELDS WITH VARIABLE LENGTH FIELDS
line 60000 above is different from the equivalent line in the error check subroutine given Field Name Length Field Name Length
earlier. Here disk error number 50 is specifically ignored, because it will be generated
when the error channel is chec;ked in line 1460. We ignore it because not having a NAME 27 characters NAME 31 characters
requested record would only be ail error if that record had previously been created. STREET 27 characters STREET 31 characters
CITY & STATE 23 characters CITY & STATE 26 characters
EXPANDING A RELATIVE FILE ZIP CODE I0 characters ZIP CODE 11 characters
Total length 87 characters Potential length 99 character
What if you underestimate your needs and need to expand a relative file later? No Edited length 87 characters
problem. Simply request the record number you need, even if it doesn't currently exist in
the file. If there is no such record yet, DOS' will create it as soon as you try to write With fixed length records, the field lengths add up to exactly the record length . Since
information in it, and also automatically create any other missing records below it in the total length is just within the Input buffer size limitation, no carriage return characters
number. The only penalty will be a slight time delay while the records are created. are needed . With variable length records , we can take advantage of the vatiability of
actual address lengths . While one name contains 27 letters , another may have only 15 ,
and the same variability exists in Street and City lengths . Although variable length records
lose I character per field for carriage returns, they can take advantage of the difference
61
60
between maximum field length and average field length . A program that uses variable 30 IF LEN(SA$)>27 THEN 2020
record lengths must calculate the total length of each record as it is entered, to be sure the ~35 SA$= SA$+ LEFT$(BL$,27-LN)
total of all fields doesn't exceed the space available. z()40 (NPUT"CITY & STATE" ;CS$
2()45 LN = LEN(CS$)
WRITING THE RECORD 2()50 IF LEN(CS$)>23 THEN 2040
2()55 CS$= CS$+ LEFT$(BL$,23-LN)
Here is an example of program lines to enter variable length fields for the above file zf11J INPUT"ZIP CODE";ZP$
design, build them into a single string, and send thc;m to record number RE in file number 2()65 LN = LEN(ZP$)
3 (assumed to be a relative file that uses channel number 3). 'df/O IF LEN(ZP$)> 10 THEN 2060
'df/5ZP$=ZP$+LEFT$(BL$,10-LN)
150 CR$=CHR$(13) Carriage Return 2()80 DA$ =NA$+ SA$+ CS$+ ZP$ Note lack of separators
2120 RH= INT(REJ256)
2000 INPUT"NAME";NA$ Enter fields 2130 RL = RE-256*RH
2010 IF LEN(NA$)>30 THEN 2000 And check length of each 2140 PRINT#l5, "P" +CHR$(96+ 3) +
2020 INPUT"STREET";SA$ CHR$(RL) + CHR$(RH1 + CHR$ (I)
2030 IF LEN(SA$)>30 THEN 2020 2150 GOSUB 59990
2040 INPUT"CITY & STATE" ;CS$ 2160 PRINT# 3 ,DA$; Note added semicolon
2050 IF LEN(CS$)>25 THEN 2040 2170 GOSUB 59990
2060 INPUT"ZIP CODE";ZP$ 2180 PRINT#l5,"P" +CHR$(96+ 3) +
2070 IF LEN(ZP$)> 10 THEN 2060 CHR$(RL) + CHR$(RH) + CHR$ (I)
2080 DA$=NA$+CR$+SA$+CR$+ 2190 GOSUB 59990
CS$+ CR$+ ZP$ Build output data string
2090 IF LEN(DA$)<87 THEN 2120 Check its length If field contents vary in length, variable field lengths are often preferable. On the
2100 PRINT"RECORD TOO LONG" If too long overall Olhcr hand, if the field lengths are stable, fixed field lengths are preferable . Fixed length
2110 GOTO 2000 fields are also required if you want to use the optional offset parameter of the. Record#
2120 RH= INT(RE/256) Calculate record number command to point at a particular byte within a record. However, one warning must be
2130 RL=RE-256*RH made about using the offset this way . When any part of a record is written, DOS
2140PRINT#15, "P" + CHR$(96 + 3) + overwrites any remaining spaces in the record. Thus, if you must use the offset option ,
CHR$(RL) + CHR$(RH) Position to record number RE never update any field in a record other than the last one unless all succeeding fields will
2150 GOSUB 59990 Check for disk errors also be updated from memory later.
2160 PRINT#3,DA$ Send data to it The above programs are careful to match record lengths exactly to the space
2170 GOSUB 59990 available. Programs that don't do so will discover that DOS pads short records out to full
2180 PRINT#15, " P" +CHR$(96 + 3)+ size with fill characters, and truncates overlong records to fill only their allotted space.
CHR$(RL) + CHR$(RH) Re-position for safety When a record is truncated , DOS will indicate error 51 , ''RECORD OVERFLOW'' , but
2190 GOSUB 59990 short records will be accepted without a DOS error message .
To use the above program lines for the version with fixed length fields , we would
alter a few lines as follows : READING A RELATIVE RECORD
150 Not needed this time Once a relative record has been written properly to diskette, reading it back into
160BL$=" 27 shifted space characters COmputer memory is fairly simple, but the procedure again varies, depending on whether
it USes fixed or variable length fields . Here are the program lines needed to read back the
2000 INPUT"NAME" ;NA$ Variable fields created above from record number RE in file and channel 3:
2005 LN = LEN(NA$)
2010 IF LEN(NA$)> 27 THEN 2000 Checking for different lengths Jooo RH= INT(RE/256) Calculate record number
2015 NA$= NA$+ LEFT$(BL$ ,27-LN) And padding to preset sizes 3010 RL=RE-256*RH
2020 INPUT"STREET" ;SA$ 3020 PRINT#l5,"P" +CHR$(96+3)+
2025 LN = LEN(SA$) CHR$(RL) + CHR$(RH) + CHR$ ( 1) Position to record number RE
62 63
3030 GOSUB 59990 Check for disk errors
3040 INPUT# l ,NA$,SA$,CS$,ZP$ Read in fields
3050 GOSUB 59990
CHAPTER 7
DIRECT ACCESS COMMANDS
3060PRINT#15 , "P" + CHR$(96 + 3) +
CHR$(RL) + CHR$(RH) Re-position for safety
!t fOOL FOR ADVANCED USERS
Here are the lines needed to read back the version with fixed length fields :
Direct access commands specify individual sectors on the diskette , reading and
writing information entirely under your direction . This gives them aln:io.st .complete
3000 RH= INT(RE/256)
oexibility in data-handling proerams, but also imposes tremendous respons1b1httes on t~e
3010 RL=RE-256*RH
programmer, to be sure nothing goes awry . As a res~Jt, they a~e normally used only. m
3020 PRINT#l5 , "P" +CHR$(96+ 3) +CHR$
complex commercial programs able to properly organize data without help from the disk
( RL) + CHR$(RH)
3030 GOSUB 59990 drive itself. . . ..
A far more common use of direct access commands 1s m utility programs used to
3040 INPUT# 1,DA$ Read in entire record view and alter parts of the diskette that are not normally seen directly. For i.nstance, su~h
3050 GOSUB 59990
onunands can be used to change the name of a diskette without erasing all of its
3060 PRINT#l5 ,"P" +CHR$(96+3)+
CHR$(RL) + CHR$(RH)
~grams, to lock a program so it can't be erased , or hide your name in a location where it
won't be expected .
3070 NA$= LEFf$(DA$,27) Split data into fields
3080 SA$= MID$(DA$,28 ,27)
DISKETTE ORGANIZ~ TION
3090 CS$= MID$(DA$ ,55 ,23)
3100 ZP$ = RIGHT$(DA$ , 10)
There are a total of 683 blocks on a 1541 diskette , of which 664 are available for use ,
with the rest reserved for the BAM (Block Availability Map) and the Directory .
This ends our discussion of relative files . A complete "RELATIVE FILE" program, The diskette's surface is divided into tracks, which are laid out as concentric circles
similar to the examples in this chapter, is included on the Test/Demo diskette.
on the surface of the diskette . There are 35 different tracks, starting with track I at the
outside of the diskette to track 35 at the center. Track 18 is used for the directory, and the
THE VALUE OF INDEX FILES (ADVANCED USERS) DOS fills up the diskette from the center outward , alternately in both directions.
Each track is subdivided into sectors (also called blocks) . Because there is more
In the last two chapters we have learned how to use sequential and relative files room on the outer tracks, there are more sectors per track there . The outermost tracks
separately. But they are often used together, witti the sequentia.1 file used to keep brief contain 21 sectors each, while the innermost ones only have 17 sectors each . The table
records of which name in the relative file is stored in each record number. That way the below shows the number of sectors per track .
contents of the sequential file can be read into a string array and sorted alphabetically.
After sorting , a technique known as a binary search can be used to very quickly find an Table 6.1: Track and Sector Format
entered name in the array , and read in or write the associated record in the relative file. TRACK NUMBER SECTOR NUMBERS TOTAL SECTORS
Advanced programs can .maintain two or more such index files , sorted in differing ways
simultaneously. I to 17 0 through 20 21
18 to 24 0 through 18 19
25 to 30 0 through 17 18
31 to 35 0 through 16 17
In this chapter we will describe the DOS commands for directly reading and writing
any track and block mi the diskette, as well as the commands used to mark blocks as used
or unused . Unless otherwise notes, all direct access commands are the same in both Basic
2and Basic 3.5 .
When working with direct access data , you.need two channels open to the disk: the
conunand channel we ' ve used throughout the book , and another for data . The command
Channel is opened with the usual OPEN 15 ,8 , 15 or equivalent. A direct access data
64
65
channel is opened much like other files, except that the pound sign (#), optionaJiy 8'{AMPLE:
followed by a memory buffer number, is used as a file name.
Here is a complete program to read a sector into disk memory using U I , and from
FORMAT FOR DIRECT ACCESS FILE OPEN STATEMENTS: dJefC into computer memory via Get#. (If a carriage return will appear at least once in
every 88 characters of data, Input# may be used in place of Get#) .
OPEN file #,device#, channel#, "#buffer#"
110 MB =7936:REM ~!FOO Define a memory buffer
where "file #" is the file number, "device#" is the disk's device number, normally 8· 120 INPUT"TRACK TO READ";T Select a track
"channel#" is the channel number, a number between 2 and 14 that is not used by othe; 130 INPUT"SECTOR TO READ";S and sector
files open at the same time; and "buffer#", if present, is a 0, l, 2, or 3, specifying the 140 OPEN 15,8,15 Open command channel
memory buffer within the 1541 to use for this file's data. 150 OPEN 5,8,5,"#" Open direct access ,channel
160 PRINT#l5, "Ul ";5;0;T;S Read sector into disk buffer
EXAMPLES: 170 FOR l=MB TO MB+255 Use a loop to
180 GET#5,A$:1F A$=" " copy disk buffer
If we don't specify which disk buffer to use, the 1541 will select one: THEN A$= CHR$(0) into computer memory
190 POKE l,ASC(A$) Tidy up after
OPEN 5,8,5,"#" 200NEXT
210 CLOSE 5:CLOSE 15
Or we can make the choice ourselves: 220 END
As the loop progresses, the contents of the specified track and sector are copied into
OPEN 4,8,4,"#2" computer memory, beginning at the address set by variable MB in line 160, and may be
examined and altered there. This is the basis for programs like "DISPLAY T & S" on the
Test/Demo diskette.
BLOCK-READ BLOCK-WRITE
The purpose of a Block Read is to load the contents of a specified sector into a The purpose of a Block Write is to save the contents of a file buffer into a specified
file buffer. Although the Block Read command (B-R) is still part of the DOS1 sector. It is thus the reverse of the Block Read command. Although the Block Write
command set, it is nearly always replaced by the Ul command . command (B-W) is still part of the DOS command set, it is nearly always replaced by the
U2command.
66 67
EXAMPLES: abbreviated as: PRINT#l5 , " B-W";channel # ;drive # ;track # ;sector#
To restore track 18, sector I of the directory from the disk buffer filled by the Block where "channel # " is the channel number specified when the file into which the block
Read example on page 82, we can use will be read was opened , "drive# " is the drive number (always 0 on the 1541 ), and
·•track#" and " sector# " are respectively the track and sector numbers containing the
PRINT# 15, "U2";5;0;18;1 desired block of data to be partially read into or written from the file buffer.
We'll return to this example on the next page, after we learn to alter the directory in a
useful way. IMPORTANT NOTES:
We can also use a Block Write to write a name in Track l, Sector 1, a rarely-used
sector. This can be used as a way of marking a diskette as belonging to you . Here is a 1. In a true Block-Read , the first byte of the selected sector is used to
program to do it, using the alternate form of the Block Write command: determine how many bytes of that sector to read into the disk memory buffer. It
thus cannot be used to read an entire sector into the buffer, as the first data byte is
110 INPUT" YOUR NAME" ;NA$ Enter a name
always interpreted as being the number of characters to read , rather than part of the
120 OPEN 15,8,15 Open command channel
data.
130 ')PEN 4,8 ,4, "#" Open direct access channel
2. Similarly, in a true Block-Write, when the buffer is written back to diskette,
140 PRINT#4,NA$ Write name to buffer
the first byte written is the current value of the buffer pointer, and only that many
150 PRINT#l5 , "U2";4;0; 1; l Write buffer to Track 1,
bytes are written into the specified sector. It cannot be used to rewrite an entire
160 CLOSE4 Sector 1 of diskette
sector onto diskette unchanged, because the first data byte is overwritten by the
170CLOSE 15 Tidy up after buffer pointer. ·
180 END
THE ORIGINAL BLOCK-READ AND BLOCK-WRITE COMMANDS (EXPERT THE BUFFER POINTER
USERS ONLY)
The buffer pointer points to where the next Read or Write will begin within a disk
Although. the Block Read and Block Write commands are nearly always replaced by memory buffer. By moving the buffer pointer, you can access individual bytes within a
the U 1 and U2 commands respectively , the original commands can still be used, as long block in any order. This allows you to edit any portion of a sector, or organize it into
as you fully understand their effects . Unlike U 1 and U2 , B-R and B-W allow you to read fields, like a relative record .
or write less than a full sector. In the case of B-R, the first byte of the selected sector is
used to set the buffer pointer (see next section), and determines how many bytes of that FORMAT FOR THE BUFFER-POINTER COMMAND:
sector are read into a disk memory buffer. A program may check to be sure it doesn't
attempt to read past the end of data actually loaded into the buffer, by watching for the PR1NT#l5,"BUFFER-POINTER" ;channel #;byte
value of the file status variable ST to change from 0 to 64 . When the buffer is written back
to diskette by B-W , the first byte written is the current value of the buffer pointer, and USually abbreviated as: PRINT#l5 ,"B-P" ;channel # ;byte
only that many bytes are written into the specified sector. B-R and B-W may thus be
useful in working with custom-designed file structures . Where "channel #" is the channel number specified when the file reserving the buffer
was opened, and " byte" is the character number within the buffer at which to point.
FORMAT FOR THE ORIGINAL BLOCK-READ AND BLOCK-WRITE COM·
MANDS: ALTERNATE FORMATS:
PRINT#l5, " BLOCK-READ" ;channel # ;drive # ;track # ;sector# PRINT#l5,"B-P: " channel #;byte
PRINT#l5, "B-P:channel #;byte"
abbreviated as: PRINT# 15, "B-R" ;channel # ;drive # ;track #;sector #
£XAMJ>LE:
and
Here is a program that locks the first program or file on a 1541 diskette . It works by
PRINT#l5 ," BLOCK ~WRITE";channel # ;drive #;track # ;sector# ltading the start of the directory (Track I 8, Sector I) into disk memory , setting the buffer
68 69
pointer to the first file type byte (see Appendix C for details of directory organization), the next available track and block number. Therefore , before selecting a block to write,
locking it by setting bit 6 and rewriting it. ll'Y to allocate that block . If the block isn't available, read the next available block from
the error channel and allocate it instead. However, do not allocate data blocks in the
110 OPEN 15,8,15 Open command channel directory track . If the track number returned is 0, the diskette is full .
120 OPEN 5,8,5, "#" Open direct access channel Here is a program that allocates a place to store a message on a diskette .
130 PRINT#l5, "Ul ";5;0;18;1 Read Track 18, Sector 1
140 PRINT#l5, " B-P" ;5;2 Point to Byte 2 of the buffer 100 OPEN15 ,8,15 Open command channel
150 GET#5,A$:IF A$= " " THEN A$= CHR$(0) Read it into memory 110 OPEN5,8 ,5, " #" " direct access "
160 A=ASC(A$) OR 64 Tum on bit 6 to lock 120 PRfNT#5 , " I THrNK
170 PRINT#l5 •."B-P";5;2 Point to Byte 2 again THEREFORE I AM " Write a message to buffer
180 PRINT#5,CHR$(A); Overwrite it in buffer 130T=l :S=I Start at first track & sector
190 PRINT#l5, "U2" ;5;0;18;1 Rewrite buffer to diskette 140 PRINT#l5 ," B-A";O;T;S Try allocating it
200 CLOSE 5 Tidy up after 150 INPUT#l5,EN ,EM$ ,ET,ES See if it worked
210 CLOSE 15 160 IF EN=O THEN 210 If so, we' re almost done
220END 170 IF EN<~65 THEN PRINT
EN ,EM$,ET,ES :STOP " NO BLOCK" means already allocated
After the above program is run, the first file on that diskette can no longer be erased. If 180 IF ET=O THEN PRINT
you later need to erase that file, re-run the same program, but substitute the revised line "DISK FULL":STOP If next track is 0, we're out of room
160 below to unlock the file again: 190 IF ET= 18 THEN ET= 19:ES=O Don ' t allocate the directory!
200T=ET:S=ES:GOTO 140 Try suggested track & sector next
160 A=ASC(A$) AND 191 Tum off bit 6 to unlock 210 PRINT#l5 ,"U2";5;0;T;S Write buffer to allocated sector
220 PRrNT " STORED AT:",T,S Say where message went
ALLOCATING BLOCKS 230 CLOSE 5:CLOSE 15 and tidy up
240END
Once you have written something in a particular sector on a diskette with the help of
direct access commands, you may wish to mark that sector as "already used," to keep FREEING BLOCKS
other files from being written there. Blocks thus " allocated" will be safe until the diskette
is validated . The Block-Free command is the opposite of Block-Allocate. It frees a block that you
don't need any more, for re-use by the DOS . Block-Free updates the BAM to show a
FORMAT FOR BLOCK-ALLOCATE COMMAND: particular sector is not in use, rather than actually erasing any data.
usually abbreviated as: PRINT#l5, " B-A" ;drive #;track #;sector# PRINT#l5, " BLOCK-FREE" ;drive #;track # ;sector#
where " drive#" is the drive number, always 0 on the 1541, and "track#" and " sector abbreviated as: PRINT#l5 ,"B-F";drive # ;track # ;sector#
#'' are the track and sector containing the block of data to be read into the file buffer.
w~~re "drive#_" is the drive number (always 0 on the 1541), and "track#" and "sector
ALTERNATE FORMAT: I are respectively the track and sector numbers containing the desired block of data to
be read into the file buffer.
PRINT#l5 ,"B-A:";drive # ; track # ;sector#
ALTERNATE FORMAT:
EXAMPLE:
PRINT#l5,"B-F:";drive # ;track #;sectoi #
•lf you try to allocate a block that isn' t available, the DOS will set the error message
to number 65 , NO BLOCK , and set the track and block numbers in the error message to
70 71
EXAMPLE: CHAPTERS
INTERNAL DISK COMMANDS
To free the sector in which we wrote our name in the Block Write example, and
allocated in the first Block-Allocate example, we could use the following command: Expert programmers can give commands that directly alter the workings of the 1541,
111 uch as skilled programmers can alter the workings of Basic inside the computer with
PRINT#l5 ,"B-F" ;O;l;I feeks, Pokes and Sys calls . It is also possible to write machine language progral\JS that
load and run entirely within the 1541 , either by writing them into disk memory from the
USING RANDOM FILES (ADVANCED USERS ONLY) computer, or by lOll.ding them directly from diskette into the desired disk memory buffer.
In use, this is similar to loading and running machine language programs in your
By combining the commands in this chapter, it is possible to develop a file. computer.
handing program that uses random files. What you need to know now is how to As when learning to use Peek(), Poke and Sys in your computer, extreme caution is
keep track of which blocks on the disk such a file has used. (Even though you know advised in using the commands in this chapter. They are essentially machine language
a sector has not been allocated by your random file, you must also be sure it wasn' t commands, and lack all of Basic's safeguards . If anything goes wrong , you may have to
allocated by another unrelated file on the diskette.) tum the disk drive off and on again (after removing the diskette) to regain control. Do not
The most common way of recording which sectors have been used by a random file is practice these commands on any important diskette . Rather, make a spare copy and work
in a sequential file. The sequential file stores a list of record numbers, with the track, with that. Knowing how to program a 6502 in machine language will help greatly , and
sector, and byte location of each record . This means three channels are needed by a you will also need a good memory map of the 1541 . A brief 1541 map appears below .
random file: one for the command channel, one for the random data, and the last for the
sequential data. 1541 MEMORY MAP
Location Purpose
2K of RAM memory
0000-00FF Zero page work area: job queue , important variables & pointers
0100-0lFF Stack work area
0200-02FF Command buffers & tables : channels , parser, output, variables
0300-07FF Data buffers 0-4, 1 per page of memory .
Input/Output chips
1800-180F 6522 VIA: 1/0 to computer
ICOO-ICOF 65f2 VIA : I/O to disk controller
Disk Operating System ROM
CIOO-F258 Interface Processor: receive & interpret commands from computer
F259-FE66 Floppy Disk Controller: executes IP's commands , controls mecha-
nism
FE67-FE84 IRQ handler: switches from lP to FDC & back every 10 ms .
FE85-FEE6 ROM tables & constants
PEE7-FFOF Patch area
FFE6-FFFF JMP table: User command vectors
72 73
E)(AMPLES:
Other Resources:
More detailed information about Commodore disk drives can be found in these To see how many tries the disk will make to read a particular sector, and whether
books: ••seeks" one-half track to each side will be attempted if a read fails, and whether
Inside Commodore DOS, by lmmers & Neufeld (Datamost, cl984) " bu mps" to track one and back will be attempted before declaring the sector unreadable,
The Anatomy of the 1541 Disk Drive, by Englisch & Szczepanowski we can· use the following lines . They will read a special variable in the zero page of disk
(Abacus, c1984) memory, called REYCNT. It is located at $6A hexadecimal ($6A hexadecimal = 6 x 16
Programming the PET/CBM, by West (Level Limited, cl982) + 10 = 106).
The PET Personal Computer Guide, by Osborne & Strasmas
(Osborne/McGraw-Hill, c 1982) 1100PEN 15,8,15 Open command channel
120 PRINT# 15 , " M-R "CHR$( I06)CHR$(0) Sarne as G = PEEK(l06)
130 GET#l5,G$:IF G$= ' ' ''THEN G$ =CHR$(0)
J40 G = ASC(G$)
MEMORY -READ 150 B =G AND 128:B$= "ON":IF B THEN 8$= "OFF" Check bit 7
s
160 = G AND 64:S$ =.'ON'. :IF s THEN S$ =.'OFF' . Check bit 6
The disk contains 16K of ROM (Read-Only Memory), as well as 2K of RAM (Read- 170 T=G AND 31 :PRINT "#OF TRIES IS";T Check bits 0-5
Write Memory) . You can get direct acce~s to any location within these, or to the buffers 180 PRINT "BUMPS ARE";B$ and give results
that the DOS has set up in RAM, by using memory commands . Memory-Read allows you 190 PRINT "SEEKS ARE";S$
to select which byte or bytes to read from disk memory into the computer. The Memory- 200 CLOSE 15 Tidy up after
Read command is the equivalent of the Basic Peek() function, but reads the disk 's 210 END
memory instead of the computer's memory.
Here's a more general purpose program that reads one or more locations anywhere in disk
memory:
Note: Unlike other disk commands, those in this chapter cannot be spelled out in
full. Thus, M-R is correct, but MEMORY-READ is not a permitted alternate 110OPENl5,8,15 Open command channel
wording . 120 INPUT"# OF BYTES TO READ (O=END)";NL Enter number of bytes wanted
130 IF NL<l THEN CLOSE 15:END unless done
140 IF NL>255 THEN 120 or way out of line
150 INPUT"STARTING AT ADDRESS";AD Enter starting address
FORMAT FOR THE MEMORY-READ COMMAND: 160 AH = INT(AD/256):AL = AD-AH*256 Convert it into disk form
170 PRINT#l5, "M-R"CHR$(AL)CHR$(AH) Actual Memory-Read
PRINT# 15, " M-R " CHR$( <address)Cj-IR$(>address)CHR$(# of bytes) CHR$(NL)
180 FOR I= I TO NL Loop til have all the data
where "<address" is the low order par\ and "" >address" is the high order part of the 190 : GET#l5,A$:IF A$="" THEN A$=CHR$(0)
address in disk memory to be read. If the optional "#of bytes" is specified, it selects 200 : PRINT ASC(A$); printing it as we go
'how many memory locations will be read in, from 1-255 . Otherwise, I character will be 2IO NEXT I
read . If desired, a colon(:) may follow M-R inside the quotation marks. 220 PRINT
230GOTO 120 Forever
ALTERNATE FORMAT:
MEMORY-WRITE
PRINT# 15, "M-R: "CHR$( <address)CHR$(>address)CHR$(# of bytes)
The Memory-Write command is the equivalent of the Basic Poke command, but has
· The next byte read using the Get# statement through channel #15 (the error its effect in disk memory instead of within the computer. M-W allows you to write up to
channel), will be from that address in the disk controller's memory, and successive bytes 34 bytes at a time into disk memory. The Memory-Execute and some User commands can
will be from successive memory locations. be used to run any programs written this way .
Any Input# from the error channel will give peculiar results when you're Uiing th is
command. This can be cleared up by sending any other command to the disk, except
another memory command.
74 75
FORMAT FOR THE MEMORY-WRITE COMMAND: &fEMORY -EXECQTE
PRINT# 15 ,' 'M-W' 'CHR$( <address)CHR$(>address)CHR$ Any routine in disk memory , either in RAM or ROM , can be executed with the
(# of bytes)CHR$(data byte(s)) pJemory-Execute command. It is the equivalent of the Basic Sys call to a machine
1a11guage program or subroutine , but works in disk memory instead of within the com-
where " < address" is the low order part, and " >address" is the high order part of the puter.
address in disk memory to begin writing, "# of bytes" is the number of memory
locations that will be written (from 1-34), and "data byte " is I or more byte values to be pORMAT FOR THE MEMORY-EXECUTE COMMAND:
written into disk memory, each as a CHR$() value . If desired, a colon (:) may follow M-
W within the quotation marks. PRINT# 15,' 'M-E"CHR$( <address)CHR$(> address)
ALTERNATE FORMAT: where "<address" is the low order part, and " >address" is the high order part of the
adlfress in disk memory at which execution is to begin.
PRINT# 15 ,' 'M-W: ''CHR$( <address)CHR$(> address)CHR$
(#of bytes)CHR$(data byte(s)) ALTERNATE FORMAT:
EXAMPLES : PRINT# 15, ' ' M-E: " CHR$( <address)CHR$(> address)
We can use this line to turn off the " bumps" when loading DOS-protected programs (i.e., EXAMPLE:
programs that have been protected against being copied by creating and checking for
specific disk errors) . Here is a Memory-Execute command that does absolutely nothing. The first instruc-
tion it executes is an RTS, which ends the command:
PRINT# 15 ,' 'M-W' ' CHR$( 106)CHR$(0)CHR$( I )CHR$( 133)
PRINT#l5, ' ' M-E' 'CHR$(88)CHR$(242)
The following line can be. used to recover bad sectors. such as when an important file has
been damaged and cannot be read norrnally . A more plausible use for this command would be to artificially trigger an errO( message .
Don't forget to check the error channel, or you'll miss the message:
PRINT# 15 ," M-W' ' CHR$( I 06)CHR$(0)CHR$(1 )CHR$(3 I)
PRINT# 15, ' ' M-E " CHR$(201)CHR$(239)
The above two examples may be very useful under some circumstances . They are the
equivalent of POKE 106, 133 and POKE 106,31 respectively, but in disk memory, not However, mast uses require intimate knowledge of the inner workings of the DOS , and
inside the computer. As mentioned in the previous section's first example, location 106 in preliminary setup with other commands, such as Memory-Write.
the 1541 disk drive signifies three separate activities to the drive, all related to error
recovery . Bit 7 (the high bit) , if set means no bumps (don't thump the drive back to track BLOCK-EXECUTE
I) . Bit 6, if set, means no seeks . In that case , the drive won't attempt to read the half-track
above and below the assigned track to see if it can read the data that way . The bottom 6 This rarely-used command will load a sector containing a machine language routine
bits are the count of how many times the disk will try to read each sector before and after into a memory buffer from diskette, and execute it from the first location within the
trying seeks and bumps before giving up . Since 31 is the largest number that can be buffer, until a ReTurn from Subroutine (RTS) instruction ends the command.
expressed in 6 bits , that is the maximum number of tries allowed .
From this example , you can see the value of knowing something about Peeks, Pokes , PoRMAT FOR THE BLOCK-EXECUTI;: COMMAND:
and machine-language before using direct-access disk commands, as well as their poten-
tial power. · PRINT#I5, " B-E";channel # ;drive # ;track #;sector#
'Nbcre "channel # " is the channel number specified when the file into which the block
'Nill be loaded was opened , " drive# " is the drive number (always 0 on the 1541 ), and
"track #" and " sector # " are respectively the track and sector numbers containing the
desired block of data to be loaded into the file buffer and executed there.
76 77
ALTERNATE FORMATS: fORMA T FOR USER COMMANDS:
USER COMMANDS
Most User commands are intended to be used as machine language JMP or Basic
SYS commands to machine language programs that reside inside the disk memory.
However, some of them have other uses as well. The User! and User2 commands are used
to replace the Block-Read and Block-Write commands, UI re-starts the 1541 without
changing its variables, UJ cold-starts the 1541 almost as if it had been turned off and on
again, and UI- speeds up the 1541 when used with the VIC 20 only. (Note: VIC 20 owners
don ' t have to use UI-; the 1541 works with the VIC 20, with or without this command .)
78 79
CHAPTER9 APPENDIX A: CHANGING THE DEVICE NUMBER
MACHINE LANGUAGE PROGRAMS
SOFTWARE METHOD
Here is a list of disk-related Kemal ROM subroutines and a practical example of their
use in a program which reads a sequential file into memory from disk. Note that most One way to temporarily change the device number of a disk drive is via a program.
require advance setup of one or more processor registers or memory locations, and all are When power is first turned on, the drive reads an I/O location whose value is controlled
called with the assembly language JSR command . by a jumper on its circuit board, and writes the device number it reads there into memory
For a more complete description as to what each routine does and how parameters are Jocations 119 and 120. Any time thereafter, you may write over that device number with
set for each routine, see the Programmer's Reference Guide for your specific computer. a new one, which will be effective until it is changed again, or the 1541 is reset.
80 81
STEPS TO CHANGE THE DEVICE NUMBER USING THE SWITCH APPENDIX B: DOS ERROR MESSAGES AND LIKELY CAUSES
1. Tum off the disk drive.
2. Refer to the following chart to set the DIP SW at the back of the disk drive for device
number setting. Note: Many commercial program diskettes are intentionally created with one or
Device# swl sw2 more of the following errors , to keep programs from being improperly duplicated .
If a disk error occurs while you are making a security copy of a commercial
8 ON ON program diskette , check the program's manual . If its copyright statement does not
9 OFF ON permit purchasers to copy the program for their own use, you may not be able to
10 ON OFF duplicate the diskette. In some such cases , a safety spare copy of the program
11 OFF OFF diskette is available from your dealer or directly from the company for a reasonable
3. Tum on the disk drive. fee .
Of'F 0
This is the message ~at appears when the error channel is checked after using the
Scratch command. The track· number tells how· many files were erased .
NOTE: If any other error message numbers less than 20 ever appear, they may be
ignored . All true errors have numbers of 20 or more .
82 83
39: SYNTAX ERROR (invalid command)
24: READ ERROR (byte decoding error)
The data or header has been read into disk memory, but a hardware error has been The DOS does not recognize a command sent to the command channel (secondary
address 15). Check your typing and try again .
created by an invalid bit pattern in the data byte. May indicate grounding problems.
67 : ILLEGAL SYSTEM T OR S
This special error message indicates an illegal system track or block .
"
86 87
, ,_
88 89
1541 RELATIVE FILE FORMAT 1541 DIRECTORY FILE FORMAT
Track 18, Sector 1.
BYTE DEFINITION
DATA BLOCK BYTE DEFINITION
0, 1 Track and sector of next data block . 0, 1 Track and sector of next directory block.
2-255 254 bytes of data. Empty records contain $FF 2-31 File entry 1*
(all binary ones) in the first byte followed by $00 34-63 File entry 2*
(binary all zeros) to the end of the record. Partially 66-95 File entry 3 *
filled records are padded with nulls ($00) . 98-127 File entry 4*
130-159 File entry 5 *
SIDE SECTOR BLOCK
162-191 File entry 6*
0-1 Track and sector of next side sector block. 194-223 File entry 7*
2 Side sector number (0-5) 226-255 File entry 8*
3 Record length *STRUCTURE OF EACH INDIVIDUAL DIRECTORY ENTRY
4-5 Track and sector of first side sector (number 0)
6-7 Track and sector of second side sector (number 1) BYTE CONTENTS DEFINITION
8-9 Track and sector of third side sector (number 2) 0 128 File type OR 'ed with $80 to indicate properly closed file.
10- 11 Track and sector of fourth side sector (number 3) + (if OR'ed with $CO instead, file is locked .)
12-13 Track and sector of fifth side sector (number 4) type TYPES: 0 = DELeted
14-15 Track and sector of sixth side sector (number 5) 1 = SEQuential
16-255 Track and sector pointers to 120 data blocks. 2 = PROGram
3 =USER
4 = RELative
1-2 Track and sector of first data block.
3-18 File name padded with shifted spaces .
19-20 Relative file only: track and sector of first side
sector block.
21 Relative file only: Record length .
22-25 Unused .
26-27 Track and sector of replacement file puring an
@SA VE or @OPEN.
28-29 Number of blocks in file : stored as a two-byte integer,
in low byte, high byte order.
90 91
APPENDIX D: DISK COMMAND QUICK REFERENCE CHART APPENDIX E: TEST /DEMO DISKETTE
General Format: OPEN 15,8,15:PRINT#15,command:CLOSE 15 (Basic 2) HOW TO USE
The "HOW TO USE" programs provide brief descriptions of the other programs
HOUSEKEEPING COMMANDS
on the Test/Demo diskette.
BASIC2 NEW "NO:diskette name,id"
COPY "CO:new file=O:old file" THE VIC-20 & C-64 WEDGES
RENAME "RO:new name=old name" Additional commands are available which allow you to type short instructions to
SCRATCH "SO:file name" the disk drive. Load and run the VIC-20 WEDGE if you have a VIC; use the C-64
INITIALIZE "IO" WEDGE if you have a Commodore 64. Using either, you will be able to press backslash
VALIDATE "VO" (/) followed by the program name and the RETURN key to load a program; the "/"
means load from disk drive. For example, type "/how to use" to load that program.
BASIC 3.5 NEW HEADER "diskette name," Iid,DO Type ">" or "@" and then press RETURN to display the current disk error status.
COPY COPY "old file" TO "new file" Type">$" or"@$" and RETURN to display the directory without erasing the current
RENAME RENAME "old name" TO "new name" program.
SCRATCH SCRATCH "file name"
VALIDATE COLLECT DOSS.1
The DOS 5. I program is not intended to be loaded directly, but is loaded instead
BOTH INITIALIZE "IO"
from the program C-64 WEDGE. Its load address is $CC00 hexadecimal.
FILE COMMANDS
PRINTER TEST
BASIC2 LOAD LOAD "file name" ,8 The PRINTER TEST prints a listing of characters in a form that makes it easy to
SAVE SAVE "O:file name" ,8 check the mechanical and electronic capabilities of the printer.
SD.BACKUP .xx
These three programs are entitled SD.BACKUP.C64, SD.BACKUP.Cl6, and
SD.BACKUP.PLUS4. Each, when lo!ided into its respective computer, allows you to
create an exact duplicate of a diskette by switching a blank diskette and the diskette to
be copied in and out of the drive at the appropriate times. Loading and running them
incorrectly may damage a diskette.
PRINT .xx.UTIL
These three programs are actually entitled PRINT.64.UTIL, PRINT.+4, and
PRINT.Cl6.UTIL. They provide two functions: a printout of any Text-Mode screen
display, and a listing of the contents of all scaler (non-array) variables in a Basic pro-
gram to screen or printer. Any CBM printer may be used for either function. Printing of
reverse-video and graphics characters depends on the specific printer model used. These
programs can run from tape.
LOAD ADDRES!t
LOAD ADDRESS is a simple program that tells you where a program was origi-
nally located in memory. Some programs can only run in the same locations from which
they were saved. Load such programs with LOAD"filename'',8,1.
UNSCRATCH
Allows you to restore a file that's been deleted (scratched) from a diskette as long as
the diskette hasn't been written to since the scratch was performed.
HEADER CHANGE
Allows you to rename a diskette without losing the data currently stored in the
diskette.
IMPORTANT NOTE:
Your Test/Demo diskette
may contain additional
programs. Commodore
may update the diskette
from time to time.
94
Commodore Business Machines, Inc.
1200 Wilson Drive • West Chester, PA 19380
Commodore Business Machines, Ltd .
3470 Pharmacy Avenue• Agincourt , Ontario, Ml W 3G3