Commodore 1551 User Manual
Hirdetés
Hirdetés
COMMODORE
1551
DISK DRIVE
USERJS GUIDE
A Friendly Introduction to Your 1551 Diek Drive
The information in this manual has been reviewed and is believed to be entirely reliable.
No responsibility, however, is assumed for inaccuracies. The material in this manual is for information purposes only, and may be changed without notice.
© Commodore Electronics Ltd., October 1984
"All rights reserved."
CONTENTS
INTRODUCTION ...................................................... 1
Advantages of a disk drive. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 1
Features of the 1551 ..•.•....................................... 1
How to use this book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
PART ONE: GUIDE TO OPERATION .................................... 3
CHAPTER 1: DISK DRIVE .........•................................... 3
Unpacking ........•..................................•........ 3
Connecting the cables . . . • . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4
Turning on the power. . . • . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 5
Troubleshooting guide .......................................... 6
Simple maintenance tips. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 7
CHAPTER 2: DISKETTES ..............•............................... 9
What is a diskette? .•...•.......•..........................•.... 9
Safety rules for diskette care .....•.............................. 10
Using packaged programs .......•.............................. 10
How to prepare a new diskette ...•..........•...............•... 12
Organizing a diskette library. . . . . . . . . . . . . . . . . . . . . . . . . . . . • . . . . . .. 12
Backups ......................•................... ' ........... 13
What is a directory? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 13
Viewing a directory. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 14
What a directory shows ........................................ 14
CHAPTER 3: OPERATION . . . . . • . . . . . . . • . . . . . . . . . . . • . . . . . . . . • . . . . . . . .. 16
The command channel . . . . . . . . . . . . . . • . . . . . . . . . . . . . . . . . . . . . . . . .. 16
Error checking. . . . . . . . . . . . . . . . . . . . . • . . . . . . . . . . . . . . . . . . . . . . . . .. 17
Error check subroutine ......................................... 17
BASIC housekeeping hints. . . . . . . . . . . • . . . . . . . . . . . . . . . . . . . . . . . . .. 17
More about directories. . . . . . . . . . . . . . • . . . . . . . . . . . . . . . . . . . . . . . . .. 18
Selective directories ............................................ 19
Printing a directory. . . . . . . . . . . . . • . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 19
Pattern matching and wild cards ................................. 19
Splat files ..•......................•.......................... 20
Verify .•......................•.............................. 22
Copy ..•....•................................................ 23
Scratch •..............•..•....•.......•..............••...... 24
Rename •......................•.............................. 26
Renaming and scratching troublesome files (advanced users) ......... 26
Collect. ....•..•......................•.....................•. 27
Initialize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . • . . . . . . . . . . . . . . . . . . . . .. 28
PART TWO: GUIDE TO ADVANCED OPERATION AND PROGRAMMING 31
CHAPTER 4: SEQUENTIAL DATA FILES ............................... 31
The concept of files ............................................ 31
Opening a file. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 32
Adding to a sequential file .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 34
Writing file data: Print # ....................................... 35
Closing a file when you are done using it . . . . . . . . . . . . . . . . . . . . . . . . .. 37
Reading file data: Input # ...................................... 38
More about Input # (advanced users) ............................ 39
Numeric data storage on diskettes ................................ 40
Reading file data: Get # ........................................ 41
CHAPTER 5: RELATIVE FILES ................•...................... 44
The value of relative access ..................................... 44
Files, records, and fields ........................................ 44
File limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 45
Creating a relative file .......................................... 45
Using relative files: Record # command ........................... 46
Completing relative file creation ................................. 48
Expanding a relative file. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 49
Writing relative file data ........................................ 50
Designing a relative record. . . . . . . . . . . . . . . . • . . . . . . . . . . . . . . . . . . . .. 50
Writing the record ....................•........................ 51
Reading a relative record. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 53
The value of index files (advanced users) .......................... 54
CHAPTER 6: DIRECT ACCESS COMMANDS ........................... 55
A tool for advanced users. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 55
Diskette organization .......................................... 55
Opening a data channel for direct access . . . . • . . . . . . . . . . . . . . . . . . . .. 55
Block-read ................................................... 56
Block-write. . . . . . . . • . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 57
The original Block-read and Block-write commands . . . . . . . . . . . . . . .. 58
The buffer pointer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 59
Allocating blocks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 60
Freeing blocks ....••.......................................... 61
Using random files (advanced users) .............................. 62
CHAPTER 7: INTERNAL DISK COMMANDS .......•.........•.......... 63
1551 memory map .............•............................... 63
Memory-read ................................................. 64
Memory-write .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 65
Memory-execute .........................................•.... 66
Block-execute ...•.........•................•.................. 67
User commands .••....................•....................... 68
CHAPTER 8: MACHINE LANGUAGE PROGRAMS ...................... 70
Disk-related kernal subroutines .................................. 70
APPENDICES ........................................................ 71
A: Changing the device number ................................. 71
B: DOS error messages and likely causes ...........•............. 73
C: Diskette formats ........................................... 77
D: Disk command quick reference ............................... 82
E: Test/Demo diskette ......................................... 83
F: Specifications of the 1551 disk drive ........................... 86
LIST OF FIGURES
Figure 1: Front panel
Figure 2: Back panel
Figure 3: Single and twin drive hookup
Figure 4: Position for diskette insertion
INTRODUCTION
The 1551 disk drive greatly increases the speed, storage capacity, flexibility and reliability of your Commodore computer. As you use the 1551 disk drive, you will appreciate its superiority to the cassette recorder you may have used before and to disk drives offered for other brands of computers.
THE ADV ANT AGES OF A DISK DRIVE
• 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
1551 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 1551 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 crase a valuable program by saving a new program on top of the old one, without realizing it. The 1551 automatically verifies everything it records.
• Direct File Access
A third advantage of a disk drive is the ability to use relative files (discussed in Chapter
6). On a diskette, any part of a relative file can be accessed and altered separately, without affecting the rest of the file.
Overall, using a disk drive makes for easier and more powerful computing.
FEATURES OF THE 1551
The 1551 is one of the most affordable disk drives on the market. Compared to competitors, it has high capacity, and even higher intelligence. It is one of the most co,teffective disk drives available. Most home and personal computers that use a disk take at least 10K 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 being used, and much of it must also be kept on every diskette.
The Commodore 1551 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 other task, effectively allowing you to do two things at once.
Another key advantage of the Commodore 1551 over disk drives for other computers is its dynamic allocation of disk space. Many other disk drives make you think about every program you save. Where can I store it on this diskette, and should I paek the disk
first? (Packing is the process of moving all the leftover work areas to the cnd of the diskette's storage space.) All this is handled automatically on Commodore disk drives.
The 1551 always knows where the next program will go, and automatically fits it into the best available spot.
Diskettes created on the 1551 are read and writc compatible with Commodore 1540/
1541,4040, and 2031 disk drives. That means that diskcttes can be used interchangeably on any of these systcms. In addition, the 1551 can read programs created on the older
Commodore 2040 drives.
The 1551 is connected to the computer through the "TCBM" interface. This interface is specially created by Commodore. Bytes are transferred as parallel data with a
3-bit bi-directional port, two handshake lines, and two status lines. This handshake protocol allows for less timing constraint than the slower serial interfaces. Estimated data rate over the TCBM handshake is 1600 bytes per second versus 300-400 bytes per second for the 1541 drive. The 1551 connector plugs into the host computer's expansion port and allows external cartridges to be plugged in. You can have two 1551 drives, two 1541 drives, and two printers hooked up to the computer at once as long as each peripheral is assigned a different device number. When there is contention with duplicate device numbers, the 1551 has priority over the 1541.
HOW TO USE THIS BOOK
This book is divided into two main parts. The first part gives you the information you need to use the 1551 effectively, even if you know little or nothing about programming.
This part of the book tells you how to set up the system, how to prepare diskettes for use, how to read a directory, how to load programs, and various commands. Part two of the book is for advanced users and those who would like to become advanced users. This part provides more advanced commands, tells about the different files the 1551 uses, and how to manage them, as well as giving a few hints for machine language programmers.
Both beginning and advanced users will find valuable information in the appendices-a quick reference list of disk commands, a list of disk error messages and what they mean, specifications for the ISS\, how to use two or more disk drives at once, and explanations of some programs on the Test/Demo diskette packed with your 1551.
If you are interested only in using pre-packaged programs such as educational or recreational software, you can turn to the section entitled "Using packaged programs" in
Chapter 2. First of all, you'll have to hook up your disk drive according to the directions in Chapter I.
2
PART 1: GUIDE TO OPERATION
CHAPTER 1
DISK DRIVE
UNPACKING
The first thing you will need to do with your disk drive is unpack it. Inside the carton in which you found this manual, there should also be: a 1551 disk drive, a gray power r
. -
- - - - - - - - - l5: commodore
111I1I1I1I1II1II1I1II11I1I1I15~
1
I
-
~_Jl()
I
I
\
~~
\ \
\' l
I
\ DOOR LEVER
"=-'
DRIVE INDICATER (RED LED) LIGHT
POWER INDICATER
FLASH
(GREEN LED) LIGHT: POWER ON
ACT IVE
ERR OR
Figure 1. Front Panel
3
cord, and an interface cable with a connection for a memory expansion bus. The connector can also be hooked up to another 1551 and a cartridge. Also included is a Test/
Demo diskette and a warranty card to be filled out and returned to Commodore.
Please don't connect anything until you've read the next three pages. It could save you a lot of trouble.
After unpacking the unit, make sure nothing is inside the disk drive. If you turn the power off or on with a diskette in the drive, you could lose its contents.
To check whether the drive is empty, simply rotate the lever on the front of the disk drive counter-clockwise until it stops (see Figure 1), one-quarter tum at most. Then reach inside the long slot the lever covers when it points down, and pull out the cardboard shipping spacer inside. Don't throw it away. You will want to put it back inside the slot any time you move or ship the disk drive later.
CONNECTING THE CABLES
The power cable plugs into the back of the disk drive at one end, and into a grounded
(3-prong) outlet at the other end. It will only go in one way. Before you plug it 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 left side (see Figure 2). It is off when the portion marked "off' is pushed inward. Leave your whole system off until everything is connected.
After plugging the power cord into the disk drive and a suitable outlet, take the interface connector and insert it into the Memory Expansion slot of your computer. That's all there is to it (see Figure 3).
If you have another 1551 disk drive, plug that interface connector into the slot in the first interface connector. Don't try to use more than one disk drive until you've learned how to change their device numbers, as no two disk drives can have the same device number. We'll cover ways of changing disk device numbers in Appendix A. Until you are ready to read that section, you may find it easier to leave your extra drive(s) unconnected
(see Figure 4).
POWER SWITCH
Figure 2. Back Panel
4
FUSE/HOLDER
Single Drive
Multiple Drive
Figure 3. Disk Drive to Computer Hookup
TURNING ON THE POWER
With everything hooked up, and the disk drive empty, it is time to turn on the power.
You can turn on the power to the drive and any other devices that may be connected in any order you like. Just be sure to either turn on the power to the computer itself last, or to use a multiple outlet power box with a master switch to turn everything off and on at once.
When everything is on, including the computer, the disk drive will go 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 red light below the drive door once, and the green power-on light to the left of the drive door will glow continuously. At the same time, the computcr will be going through a similar self-test, and displaying its hello message on your TV or video monitor. Once the red 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.
5
TROUBLESHOOTING GUIDE
Symptom
Green indicator light on the 1551 not on
Cause
Disk drive not turned on
Power cable not plugged in
Power off to wall outlet
Bad fuse in disk drive
Remedy
Make sure power switch is in the "on" position
Check both ends of power cable to be sure they are fully inserted
Replace fuse or reset circuit breaker in house
Replace fuse (located on back panel, as shown in Figure 2) with one of same size and rating
(If any fuse fails twice, added help is needed. If the house fuse failed, you may need an electrician. If the drive fuse failed, call your dealer.)
Red error light on drive flashes continously on power-up, before any disk commands have been given
The disk drive is failing its power-on self-test
Tum the system off for a minute and try again.
If it repeats, try again with the interface cable disconnected. If it still repeats, call your dealer. If unplugging the interface cable made a difference. check the cable for proper connection.
(The principle behind unplugging the interface 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 1551.)
Programs won't load, and computer says "DEVICE
NOT PRESENT ERROR."
Interface connector not well connected, or disk not turned on.
Be sure interface connector is correctly inserted and disk drive is turned on
Programs won't load, but computer and disk drive give no error message.
Another device in the memory expansion slot may be interfering.
Unplug all other devices on the computer. If that cures it. plug them in one at a time. The one just added when the trouble repeats is most likely the problem.
Also, trying to load a machine language program into BASIC space will cause this problem.
(Such devices may not be turned on properly, or may have conflicting device numbers. Only one device on the cable can have anyone device number.)
6
TROUBLESHOOTING GUIDE
Symptom Cause Remedy
Programs won't load, and disk error light flashes.
A disk error has occurred.
Check the disk error channel to see why the error occurred. Follow the advice in Appendix B to correct it.
(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 called when it was saved on the diskette.)
Your own programs Load fine, but commercial programs and those from other 1551 owners fail to load.
Either the diskette you are loading is faulty,
(some mass-produced diskettes are) or your disk drive is misaligned.
Try another copy of the troublesome programs. If several programs from several sources al ways fail to load, have your dealer align your disk drive.
Your own programs that used to Load won't any more, but programs saved on newly-formatted diskettes still work.
Older diskettes have been damaged.
The disk drive has gone out of alignment.
See the section on safety rules for diskette care.
Recopy from backups.
Have your dealer align your disk drive.
SIMPLE MAINTENANCE TIPS
Your 1551 should serve you well for years to come, but there are a few things you can do to avoid costly maintenance.
1. Keep the drive well-ventilated. Like a refrigerator, it needs a few inches of air circulation on all sides to work properly. If heat can't be avoided any other way, you may cool the drive by placing a small filtered fan on the drive so its air blows into the cooling slots. (An inexpensive air freshener is quite suitable for this.) However, the added air flow will result in more dirt getting in the drive.
2. Use only good quality diskettes. Badly-made diskettes could cause increased wear on the drive's read/write head. If a particular diskette is unusually noisy in use, it is probably causing added wear, and should be replaced.
3. Avoid using programs that "thump" the drive as they load. Many commercial programs, and diskettes that are failing, cause the disk drive to make a bumping or 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 is intentional and will have to be endured.
4. It would be a good idea to have your 1551 checked over about once a year in normal use. Several items are likely to need attention: the felt load pad on the read/write head may
7
be dirty enough to need replacement, the head itself may need a bit of cleaning (with 91 % isopropyl alcohol on a cotton swab), the rails along which the head moves may need lubrication (with a special Molybdenum lubricant, NOT oil), and the write protect sensor may need to be dusted to be sure its optical sensor has a clear view. Since most of these chores require special materials or parts, it is best to leave the work to an authorized
Commodore service center. If you wish to do the work yourself, ask your dealer to order the 1551 maintenance guide for you (part number 990445), but be aware that home repair of the 1551 will void your warranty.
8
CHAPTER 2
DISKETTES
WHAT IS A DISKETTE?
Before we actually begin using the drive, let's take a moment to look at the
Test/Demo diskette packed with the disk drive. To do this, grasp it by the label, which should be sticking out of the paper jacket. Then pull it out of the jacket which keeps it free of dust and other contaminants. (Save the jacket; the diskette should always be kept in its jacket except when actually in use in the disk drive.) It is often called a floppy diskette, because it is flexible, but do not bend it.
A diskette is much like a cassette tape, but in the form of a circle and enclosed within a protective square plastic cover. As on a cassette tape, only a small exposed portion of the magnetic recording surface is sensitive. Avoid touching the few small portions that are not covered by the protective cover. Also, never try to remove this cover. Unlike the paper jacket, the plastic diskette cover is intended to remain on permanently.
Next, notice the notch on one side of the diskette (it may be covered by a piece of tape). This notch is called the write-protect notch. When it is covered with the opaque tape packed with blank diskettes, the disk drive cannot change the contents of that diskette.
Never remove the tape on the Test/Demo diskette.
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 door is closed, and its edges are clamped. This keeps them from slipping, when the diskette spins at 300 RPM in use.
The oval opening in the diskette opposite the label is called the access slot. It exposes just enough of the diskette's surface for the read/write head and load pad inside the drive to touch a one inch long line from the center to the edge of the diskette's working surface.
The bottom side of that slot is where all the information is written as the diskette spins.
To insert a diskette. first open the drive door by rotating the door lever counterclockwise one quarter tum until it stops, with the lever level with the slot in the front of the drive.
WRITE
PROTECT
NOTCH
WHEN COVEREO, DISKETTE
CONTENTS CANNOT BE
AL TERED
Figure 4. Position for Diskette Insertion
9
Z en m
:ll
-4
Z
-4
o o
:ll c::J <
C==:J m
=
Grasp the diskette by the side opposite the large oval access slot, and hold it with the label up and the write-protect notch to the left (See Figure 4). Now insert the diskette by pushing it straight into the slot, the access slot going in first and the label last. Be sure the diskette goes in until it stops naturally, with no part showing outside the drive, but you shouldn't have to force or bend it to get it there.
With the diskette in position, seat it properly for use by twisting the door lever clockwise one-quarter turn. vertically over the slot until it stops. If it does not move easily, stop' You may have put the diskette in the wrong way, or incompletely. If that happens, reposition the diskette until the door lever cluses easily.
SAFETY RULES FOR DISKETTE CARE
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 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 not allow them to become bent or folded. Since the working part of the diskette is on the bottom, never set it down on a table top or other place where dust or moisture might affect it, and be especially careful to keep your fingers away from the openings in the diskette cover.
3. Although some people sell kits intended to "double your diskette's capacity" by cutting an extra write-protect notch into a diskette, it is best not to use the other side of the diskette on the 1551 drive, even if your diskette is labeled "double-sided." Doing so will cause added wear to your diskettes and drive, and may cost you an important program some day.
4. When buying diskettes, you may use any good quality 5'/4 inch diskette.
5. Although the hub assembly will correctly center most any diskette, it would be very difficult to rescue data from a diskette recorded with its hub off-center. You can make it easier for the drive to center a diskette on the spindle by buying diskettes that come with reinforced hubs. These hard plastic rings around the hub opening make the diskette hub more rigid, and easier to center properly.
6. Always remove diskettes before turning a drive off or on. If a diskette is in place and the door closed at power on or off, you could lose part or all of the data on that diskette.
7. Similarly, do not remove a diskette from its drive when the red drive activity light is on. That light only glows when the drive is actually in use. Removing the diskette with it on may result in your losing information currently being written to the diskette.
USING PACKAGED PROGRAMS
To use prepackaged BASIC programs available on diskette, here is the procedure:
After turning on your computer system, carefully insert the preprogrammed diskette as described previously. For purpose of demonstration, use the Test/Demo diskette included with the disk drive. The following command will load a program from the diskette into the computer:
10
DLOAD "program name"
Example: DLOAD "HOW TO USE"
After each command press the RETURN key
The exact name of the program you want to load is placed between quotation marks.
After you type in the command and press the RETURN key, the following will appear on the screen:
SEARCHING FOR "HOW TO USE"
LOADING
READY .
•
When the word READY and the flashing cursor reappear on the screen and the red light goes off on the drive, the program named "HOW TO USE" on the Test/Demo diskette has been loaded into the computer's memory. To use it, just type the word RUN and press the RETURN key.
If a program isn't written in BASIC, it may require a different loading method, which may be indicated in the instructions that accompany the program package. The format for that command is:
LOAD "Program name", 8, 1 (press RETURN)
This command is used for machine language programs, which are covered in more detail later. At this point, however, try this command if a program doesn't load properly using the other command.
IMPORTANT NOTE:
Throughout the rest of this manual, when the format for a command is given, anything that is capitalized must be included as is when you type in the command.
Anything in lower case is more or less a definition of what belongs there. For instance, in the format for the HEADER command given below, the word
HEADER, the capital I in lid, the capital D in Ddrive #, and the capital U in
Udevice # must all be typed-in as is.
On the other hand, diskette name tells you that you must enter a name for the diskette, but it is up to you to decide what that name will be. Also, the id in lid is left to your discretion, as are the drive # in Ddrive #, and the device # in Udevice
#. Be aware, however, that there are certain limits placed on what you can use. In each case, those limits are explained immediately following the format.
Also be sure to type in all punctuation exactly where and how it is shown in the format.
11
HOW TO PREPARE A NEW DISKETTE
A diskette needs a pattern of magnetic grooves in order for the drive's read/write head to find things on it. This pattern is not on your diskettes when you buy them, but you can use the HEADER command to add it to a diskette. Here is the procedure:
FORMAT FOR THE HEADER COMMAND
HEADER "diskette name" ,Iid,Ddrive #,Udevice #
Where:
"diskette name" is any desired name for the diskette, up to 16 characters long (including spaces); "id" can be any two characters as long as they don't form a BASIC keyword
(such as IF or ON) either on their own or with the capital I before them; "drive #" is 0
(the 1551 assumes 0 even if you don't type it in); "device # is 8, unless you have changed it as per instructions in Appendix A (the 1551 assumes 8 even even if you don't type it in).
Note to Advanced Users:
The "id" cannot be a variable. For example, "A$" can be used, but the id would be the letter "A" and the dollar sign, not the contents of the variable. If you need a variable id, use the following command:
OPENI5,8,15:PRINT#15, "NO:MY DISK," + A$:CLOSEIS where A$ is a two character string variable.
The chattering or thumping noise you hear just after the HEADER command begins is entirely normal. The drive must be sure it is at track I, which it assures by stepping outward
4S
times (on a 35 track diskette). The noise you hear is the head assembly hitting the track 1 bumper after its inevitable arrival.
After you have once formatted a particular diskette, you can re-format it at any time, using the above procedures. However, you can also change its name and erase its programs more quickly and easily by omitting the ID number in your format command.
By leaving off the lD number, the format command will finish in a few seconds instead of the usual 90 seconds.
ORGANIZING A DISKETTE LIBRARY
Though you may not believe it now, you will eventually have dozens, if not hundreds of diskettes. You can ease life then by planning now. Assign each diskette a unique lD number when you format it. There are diskette cataloging programs you can buy, that store and alphabetize a list of all your file names, but are of limited value unless your diskette ID numbers are unique.
At least two valid approaches are used in assigning ID numbers. One starts at 00 with the first diskette, and continues upward with each new diskette, through 99, and then
12
onward from AA through ZZ. Another organizes diskettes within small categories, and starts the 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 could have 10 numbers that begin with "T." Either approach works well when followed diligently.
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.
BACKUPS
When to do a Backup
Although the 1551 is far more reliable than a cassettc drive under most circumstances, its diskettes arc still rclatively fragile, and have a useful life of only a few years in steady use. Therefore, it is important to make regular backups of important programs and files. Make a backup whencver you wouldn't want to redo your current work. Just as you should save your work every half hour or so when writing a new program, so you should also back up the diskette you're using at least daily while you are changing it frequently.
In a business, you would make an archival backup every time important information was due to be erased, such as when a new accounting period begins.
How to do a Backup
We have included a program on the Test/Demo diskette that can be used for similar purposes. This program is described further in Appendix E.
How to Rotate Backups
Once you begin to accumulate backups, you'll want to recycle older ones. One good method is to date each backup. Then retain all backups until the current project is finished.
When you are sure the last backup is correct, make another backup of it to file, and move all older backups to a box of diskettes that may be reused.
One other popular approach, suited to projects that never end, is to rotate backups in a chain, wherein there are son backups, father backups, and grandfather backups. Then, when another backup is needed, the grandfather diskette is reused, the father becomes the grandfather, and the son becomes the father.
Whichever approach is used, it is recommended that the newly-made backup becomc the diskette that is immediately used, and the diskette that is known to be good should bc filed away as the backup. That way, if the backup fails, you'll know it immediately, rather than after all the other backups have failed some dark day.
WHAT IS A DIRECTORY?
One of the primary advantages of a disk drive is that it can, with nearly equal ease and speed, access any part of a diskette's surface, and jump quickly from one spot to another. A OAT ASSETTE '", on the other hand, usually reads a cassette file from the beginning to the end, without skipping around. To see what's on a cassette, it is necessary to look at its entire length, which could take as long as an hour. On a disk drive, by way of contrast, it is a quick and simple matter to view a list of the programs and data files on a diskette. This list is called the directory.
13
VIEWING THE DIRECTORY
To view the directory, simply type the word DIRECTORY on a blank line, and press the RETURN key. This does not erase anything already in BASIC memory, so you can safely ask for a directory at almost any time, even from within another program.
You may slow a directory listing by holding down the COMMODORE key (C =), or halt it entirely by pressing the STOP key. You may also pause it with CONTROL-S (by holding down the CONTROL key while pressing the "S" key), and resume by pressing any other key.
WHAT A DIRECTORY SHOWS
Let's look at a typical directory on the Test/Demo diskette packed with your 1551 disk drive.
READY.
0
14 -HOW TO USE" PRG
12 -HOW PART 2-
12 -HOW PART 3-
4
-VIC-20 WEDGE"
4
9
4
S
4
14
9
PRG
PRG
PRG
-C-S4 WEDGEPRG
-DOS
~.l-
PRG
-PRINTER TEST" PRG
IMPORT ANT NOTE:
-DISK ADDR CHAt-«iE" PRG
Your Test/Demo diskette
-V lEW BAMPRG
may contain additional programs. Commodore
-CHECK DISKPRG
may update the diskette
-DISPL.AY, T&S" PRG
from time to time.
-PERFORMANCE TEST" PRG
~
-SEQ.FIL.E.DEMOPRG
7
7
-SO.BACKUP.C1S"
-PRINT.S4.UTIL-
PRG
7
-SO.BACKUP.PL.US4"
10 -SO.BACKUP.CS4-
PRG
PRG
PRG
7
7
-PRINT.C1S.UTIL" PRG
-PRINT.+4.UTILPRG
30
3~
-CS4 BASIC DEMO"
-+4 BASIC DEMO-
PRG
PRG
B
7
~
-LOAD ADDRESS-
-UNSCRATCH •
-HEADER CHAt-I3E-
10 "REL.FILE.DEMO·
426 BLOCKS FREE.
PRG
PRG
PRG
PRG
14
Starting with the top line, here is what it tells us:
The 0 at the left end tells us that the 1551's single drive is drive O. If we had gotten this directory from a dual disk drive, it might have said" I" instead. The next thing on the top line of the directory is the name of the diskette, enclosed in quotation marks, and printed in reverse field. Just as each program has a name, so does the diskette itself, assigned when the diskette was formatted. The diskette name may be up to 16 characters long, and serves mainly to help you organize your diskette library. The two character code to the right of the name is the diskette ID, also created when the diskette was formatted, and equally useful for individualizing diskettes.
The 2A at the right end of the top line tells us that the 1551 uses version 2 of
Commodore's DOS (disk operating system), and that it, like most Commodore drives, uses format "A."
The rest of the directory contains one line per program or file, each line supplying three pieces of information about its subject.
At the left end of each line is the size of that line's file in blocks (or sectors) of 256 characters. Four blocks are equivalent to I K (1024 characters) of RAM (read/write) memory inside the computer.
The middle of each directory line contains the name of the fi Ie, enclosed in quotation marks. All characters between the quote marks are part of the name, and must be included when loading or opening that file.
The right portion of each directory line is a three character abbreviation for the file type of that entry. As we will see in later chapters, there are many ways to store information on a diskette, most of which are associated with a distinctive file type.
TYPES OF FILES A V AILABLE
Currently used file types include:
PRG
SEQ
= Program files
= Sequential data files
REL = Relative data files
USR =' User (nearly identical to sequential)
DEL = Deleted (you may never sec one of these.)
(Note: Direct Access files, also called Random files, do not automatically appear in the directory. They are discussed in Chapter 7.)
After all the directory entries have listed, the directory finishes with a message showing how many blocks of the diskette are still available for use. This number can vary from 664 on a new diskette to 0 on one that is already completely full.
15
CHAPTER 3
OPERATION
THE COMMAND CHANNEL
You can send most commands to the 1551 in two ways. One way is with direct, one-line commands. The alternate way is by sending command data to the drive through something called the command channel. We will list both methods for each command.
As you will see in the pages that follow, the first method is simpler and selfexplanatory, but the command channel needs some explanation because you must combine BASIC and disk commands. The first step is to open the channel using the BASIC open statement. The usual form of this statement is:
OPENI5,8,15
The first 15 is a file number, and although it could be any number from I to 255, for our purposes now we'll use 15. That is because it is used to match the secondary address of 15, which is the address of the command channel. The middle number is the primary address, better known as the device number, and is normally 8, unless you change it according to instructions in Appendix A.
Once the command channel has been opened, use the PRINT# command to send information to thc disk drive, and INPUT# command to receive information back from the disk drive. Once you have finished using the command channel, you must close it like this:
CLOSEI5
The following examples illustrate the use of the command channel to NEW an unformatted disk (this is the equivalent of the HEADER command described in the last chapter):
OPENI5,8,15
PRINT#15, "NEW:diskname,id"
CLOSE15
You can combine the first two statements and abbreviate the NEW command like this:
OPEN 15,8, 15, "N:diskname,id"
CLOSEI5
If the command channel is already open, you must use the following format (trying to open a channel that is already open, results in a "FILE OPEN" error):
PRINT# 15,' 'N:diskname,id"
16
ERROR CHECKING
If the disk drive error light is flashing, you must check the drive to find out what the problem is. To do that, simply type:
PRINT DS$ or abbreviate it to
? DS$
The current disk error message is then displayed on the screen. A message is displayed whether there is an error or not, but if there was an error, printing its message clears it from the disk memory and turns off the error light on the disk drive.
Once the message is on the screen, you can look it up in Appendix B to see what it means, and what to do about it.
ERROR CHECK SUBROUTINE
Since those of you who are writing programs should be checking the error status after each disk command, you may want to include a small subroutine in each program to take care of the error channel:
59990 REM READ ERROR CHANNEL
60000 IF OS> 19 THEN PRINT DS$:STOP
60010 RETURN
This subroutine reads thc error channel and puts the n:sults into the reserved variables
DS and DS$. They are updated automatically by BASIC. Two error numbers are harmless: 0 means everything is OK, and I tells how many files were erased by a
SCRATCH command (described later in this chapter). If the error status is anything else, line 60000 prints the error message and halts the program. After you have repaired the damage, you may then continue the program with BASIC's CONT command.
Because this is a subroutine, you access it with the BASIC's GOSUB command, either in immediate mode or from a program. (For example, "200 GOSUB 59990".) The
RETURN statement in line 60010 will jump back to immediate mode or the next statement in your program, whichever is appropriate.
BASIC HOUSEKEEPING HINTS
Hint #1: It is best to open file 15 once at the very start of a program. and only close it at the end of the program. after all other files have already been closed. 00 this because closing the command channel automatically closes all other disk files. By opening once at the start, the file is open whenever needed for disk commands elsewhere in the program.
Closing it at the end makes sure all disk files are properly closed without interrupting any other file commands.
I7
Hint #2: If BASIC halts with an error when you have files open, BASIC aborts them without closing them properly on the disk. To close them properly on the disk, you must type:
CLOSEI5:0PENI5,8,15:CLOSEI5
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 the entire file.
HINT #3: One disk error message is not always an error. Error 73, "CBM DOS v2.6
TDISK",O will appear if you read the disk error channel before sending any disk commands when you tum on your computer. This is a handy way to check which version of DOS you are using. However, if this message appears later, after other disk commands, it means there is a mismatch between the DOS used to format your diskette and the DOS in your drive.
HINT #4: To reset drive, type:
OPEN15,S, 15, "UJ"
Then wait until the drive activity LED is off and motor goes off, then type:
CLOSE15.
This also applies to sending a UI
+ or a UI -
MORE ABOUT DIRECTORIES
We discussed the basic elements of directories in the last chapter. Here we provide more detailed information that you can use to manipulate a directory.
As noted in the last chapter, the direct command for displaying a directory is
DIRECTORY.
The alternate command for that is:
LOAD' '$" ,device#
LIST
The direct command displays the directory without disturbing anything in the computer's memory. It also displays it from within a program when you include the command in the program. The alternate method, however, over-writes anything in memory. Another way to examine the directory from within a BASIC program is described in Chapter 5, the section dealing with the GET# statement.
18
SELECTIVE DIRECTORIES
By altering our directory LOAD command, you can create a kind of' 'sub-directory" that lists a single selected type of file. For example, you could 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. The general format for this command is:
LOAD"$O:fn = filetype" where fn is a pattern that specifies a particular group of files, and filetype is the one-letter abbreviation for the types of files listed below:
P = Program
S = Sequential
R = Relative
U
=
User
D
=
Deleted
A
=
Append
M = Modify
For instance, LOAD"$O:R
* = S" displays a sub-directory consisting of all sequential files that start with the letter R (the asterisk (*) is explained in the section "Pattern matching and wild cards ").
The command LOAD' '$0:* = R" displays all relative files.
PRINTING A DIRECTORY
To get a printout of a directory, type the following:
LOAD"$" ,8
OPEN4,4:CMD4:LlST
PRINT#4:CLOSE4
Type it in immediate mode to avoid disturbing the directory.
This command assumes a printer device# of 4.
All other options, such as differing device numbers, and selective directories can also be specified as usual.
PATTERN MATCHING AND WILD CARDS
You can use special pattern matching characters to load a program from a partial name or to provide the selective directories described earlier.
The two characters used in pattern matching are the asterisk (*) and the question mark ('1). They act something like a wild card in a game of cards, standing for anything.
The difference between the two is that the asterisk makes all characters in and beyond its
19
position wild, while the question mark only makes its own character position wild. Here are some examples, and their results:
DLOAD"A*" 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" loads the first program that starts with "SM", ends with "TH", with one other character between. That loads "SMITH" or "SMYTH", but not
"SMYTHE" .
DIRECTORY"Q*" will load a directory of files whose names begin with "Q".
When an asterisk is used alone as a name, it matches the last file used. [f 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.
You can use the pattern matching characters in any disk command that includes a pattern. This applies to LOAD, DLOAD, DIRECTORY, OPEN, SCRATCH, and to the source file in the OPEN and RENAME commands (these commands are described later in this chapter). More than one "?" can appear in the same pattern.
If you use the asterisk or question mark in pattern matching, you can't use them in a tile name when saving or writing a file (described later).
SPLA T F'ILl£S
One indicator you may occasionally notice on a directory line, after you begin saving programs and files, is an asterisk appearing just before the file type of a file that is 0 blocks long. This indicates the file was not properly closed after it was created, and that it should not be relied upon. These "splat" files (as they are called in England) will normally need to be erased from the diskette and rewritten. However, do not use the
SCRATCH command to get rid of them. They can only be safely erased by the Y ALI-
DATE and COLLECT commands (these commands are described later in this chapter).
One of these should normally be used whenever a splat file is noticed on a diskette.
There are two exceptions to the above warning: one is that Y ALI DATE and
COLLECT cannot be used on some diskettes that include direct access (random) files
(described in Chapter 7), and the other is that if the information in the splat file was crucial and can't be replaced, there is a way to rescue whatever part of the file was properly written (this is described later in this chapter).
SAVE
This command will save something you've written so you can reuse it. Before you can save it to a diskette though, the diskette must be formatted, as described in the last chapter.
FORMAT FOR THE SA YE COMMAND
DSA YE "file name" where "file name" is any string expression of up to 16 characters.
20
The alternate command is:
SA VE "drive#:file name" ,device# where "file name" is any string expression of up to 16 characters, preceded by the drive#
(always 0 on the 1551) and followed by the device# (normally 8 unless you change it to 9)
Note: the "0:" at the start of tile names is a holdover from the days when all
Commodore disks had two drives in the same cabinet. Although the 1551 will normally default to drive 0 (not having a drive I,) it is best to specify the drive number whenever saving or writing a file. This avoids potential confusion in DOS
(the Disk Operating System.)
These commands will not work in copying programs that are not written in BAS[C.
To copy these machine language programs, you will need the S command of the machine language monitor built into the Commodore 16 and Plus/4. To access a built-in monitor, type MONITOR. To exit a monitor, type X alone on a line.
FORMAT FOR A MON[TOR SAVE
S "drive #:file name" ,device # ,starting address,ending address + I where "drive #:" is the drive number, 0 on the [551; "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 1551 (the leading 0 is required): and the 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 be saved.
SA VE WITH REPLACE OPTION
If a file already exists, it can't be saved again because the disk only a[lows one copy of any given tile name per diskette. It is possible to get around this problem using the
Rename and Scratch commands described later in this chapter. However, if all you wish to do is replace a program or data file with a revised version. another command is more convenient. Known as Save With Replace, this option tells the disk to replace any file it finds in the directory with the same name. substituting the new file for it.
FORMAT FOR SAVE WITH REPLACE
DSA VE "((l·file name"
21
The alternate command is:
SA VE "@drive #:Iile name" ,device# where all the parameters are as usual except for adding a leading "at" sign (((il). In this case, the drive# is required in the alternate command.
The actual procedure is this-the new version is saved completely, then the old version is scratched, and its directory entry altered to point to the new version. Because it works this way, there is little if any danger that a disaster such as having the power going off midway through the process would destroy both the old and new copies of the file.
Nothing happens to the old copy until after the new copy is saved properly.
However, we do offer one caution--do not use @Save on an almost-full diskette.
Only use it when you have enough room on the diskette to hold a second complete copy of the program being replaced. Due to the way ((i:Save works, both the old and new versions of the file are on disk simultaneously at one point, as a way of safeguarding against loss of the program. If there is not enough room left on diskette to hold that second copy, only as much of the new version will be saved on the 1551 as there is still room for. After the command completes, a look at a directory will show the new version is present, but doesn't occupy enough blocks to match the copy in memory.
VERIFY
. This command makes a byte-by-byte comparison of the program currently in memory against a program on disk. This comparison includes .Iine links, which may be different for different types of memory configurations. What this means is that a program saved to disk on a Commodore 64 and re-Ioaded into a Plus4 wouldn't verify properly because the line links point to different memory locations. If the disk copy of the program differs at all from the copy in memory, a "VERIFY ERROR" will be displayed. This in itself doesn't mean either copy is bad, but if they were supposed to be identical, one or the other has a problem.
FORMAT FOR THE VERIFY COMMAND
VERIFY "file name" ,device# ,relocate flag where' 'file name" is any string expression, with or without pattern-matching characters, and "device#" is required and, of course, is normally 8. The relocate flag is optional. If it is present and is 1, the file will be verified at the memory location where originally saved. If it is 0, DOS begins verifying at the start of BASIC.
The following version of the command verifies a ftle that was just saved:
VERIFY "*,, ,device#
The device# is again required.
This command won't work properly after SAVE-WITH-REPLACE, however, because the last file used was the one deleted, and the drive will try to compare the deleted file to the program in memory. No harm will result, but "VERIFY ERROR" will always
22
be announced. To use VERIFY after (ZISA VE, include at least part of the file name that is to be verified in the pattern.
COpy
The COpy command allows you to make a spare copy of any program or file Gn a diskette. However, on a single drive like the 1551, the copy must be on the same diskette, which means it must be given a different name from the file copied. The source file and other files on the diskette are not changed. Files must be closed before they are copied.
FORMAT FOR THE COpy COMMAND
COPY "old file name" TO "new file name"
The alternate command is:
PRINT#15,"COPY:new file name=old file name" or abbreviated to:
PRINT# IS, "C:new file name = old file name"
To copy a file on a second disk drive with a device number of 9, we would use:
COPY "old file name" TO "new file name" ,U9
NOTE: If you want to copy a file from one diskette to another, you cannot use the
COpy command. Instead, use the copy program on the Test/Demo diskette (see
Appendix E).
USING COpy TO COMBINE FILES
The COPY command can be used to combine two, three, or four different files.
FORMAT FOR COPY (COMBINE) COMMAND
COPY"old file name!, old file name2, old file name3, old f1le name4" TO "new file name"
The alternate command is:
PRINT# 15, "C:new file name = old file name I, old file name2, old file name3, old file name4"
23
where: "old file name" is the name of two, three, or four files that you want to combine into one file ("new file name").
NOTE: The length of a command string (command and filenames) is limited to 41 characters.
SCRATCH
The SCRATCH command allows you to erase unwanted programs and files from your diskettes, and free up the space they occupied for use by other files and programs. It can be used to erase either a single file, or several files at once via pattern-matching.
FORMAT FOR THE SCRATCH COMMAND
SCRATCH "file name"
The alternate command is:
PRINT#15, "SCRATCH:filename" or abbreviated to:
PRINT# 15,' 'S:filename"
"file name" can be any file name or combination of characters and wild card characters.
If you use the direct command, you will be asked as a precaution:
ARE YOU SURE? •
If you ARE sure, simply press Y and RETURN. If not, press RETURN alone or type any other answer, and the command will be cancelled.
The number of files that were scratched will be automatically displayed. For example, if your diskette contains program files named "TEST", "TRAIN", "TRUCK", and
"TAIL", you may scratch all four, along with any other files beginning with the letter
"T", by using the command:
SCRATCH "T*" and if the four listed were the only files beginning with "T", you will see:
24
01 ,FILES SCRATCHED,04,00
READY
•
The "04" tells you 4 files were scratched.
You can perform a SCRATCH within a program, but there will be no prompt message displayed.
SCRATCH FOR ADVANCED USERS
SCRATCH is a powerful command, and should be used with caution, to be sure you only 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 deleted. That way you'll have no unpleasant surprises when you use the same pattern in the SCRATCH command.
Recovering from a Scratch
If you accidentally SCRATCH a fiJe you shouldn't have, there is still a chance of saving 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 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.
NOTE: Check Appendix E. There may be an "Unscratch" program on your
Test/Demo diskette.
More about Splat Files
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 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. 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 when you add more files to the diskette.
If you find a splat file, or if you discover too late 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 scratching the splat file, it is best to immediately copy the entire diskette onto another fresh diskette, but do this with a
25
copy program rather than with a backup program. Otherwise, the same problem will be recreated on the new diskette. When the new copy is done, compare the number of blocks free in its directory to the number free on the original 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.
Locked Files
Very occasionally, a diskette will contain a locked file; that is one which cannot be 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 locked file, you will have to use a disk
~nitor
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 byte. For more information on how such tricks are done, see Chapter 9 and
Appendices D and E.
RENAME
The RENAME command allows you to alter the name of a file in the diskette directory. Since only the directory is affected, RENAME works very ljuickly. If you try to
RENAME a file by using a file name already in the directory, the computer will respond with a "FILE EXISTS" error.
FORMAT FOR RENAME COMMAND:
RENAME "old name·' TO "new name"
The alternate command is:
PRINT#15,"RENAME:new name=old name" or abbreviated to:
PRINT#15, "R:new name = old name"
One caution be sure the file you are renaming has been properly closed before you
RENAME it.
RENAMING AND SCRATCHING TROUBLESOME
FILES (ADVANCED USERS)
Eventually, you may run across a file which has a crazy filename, such as a comma by itself (", ") or one that includes a SHIFTed SPACE. Or perhaps you will find one that includes nonprinting characters. Any of these can be troublesome. Comma files, for instance, are an exception to the rule that no two files can have the same name. Since it shouldn't be possible to make a file whose name is only a comma, the disk never expects you to do it again.
26
Files with a SHIFf-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 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 disk recognize a small part of it as being the same as the whole thing without using pattern-matching characters.
In any case, if you have a troublesome filename, you can use the Chr$() function to 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 characters discussed for 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.
For example, if you have managed to create a file named" "MOVIES", with an extra quotation mark at the front of the file name, you can rename it to "MOVIES" by using the Chr$O equivalent of a quotation mark in the RENAME command:
Example:
RENAME(CHR$(34)+ "MOVIES") TO "MOVIES"
Alternate example:
PRINT# 15, "RO:MOVIES = " + CHR$(34)+ "MOVIES"
The CHR$(34) forces a quotation mark into the command string without upsetting
BASIC. The procedure for a file name that includes a SHIFf-SPACE is similar, but uses
CHR$(I60).
In cases where even this doesn't work, for example if your diskette contains a comma file, (one named".") you can get rid of it this way:
Example:
SCRATCH"?"
Alternate example:
PRINT# 15, "SO:?"
Depending on the exact problem. you may have to be very creative in choosing patternmatching characters that will affect only the desired file. and Illay have to rename other files first to keep them from being scratched too.
COLLECT
The COLLECT command 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 sectors (blocks) are left unallocated and free for re-use, and
27
all improperly-closed files are automatically SCRATCHED. However, this bare description of its workings doesn't indicate either the power or the danger of the COLLECT command. Its power is in restoring to good health many diskettes whose directories or block availability maps have become muddled. Any time the blocks used by the files on a diskette plus the blocks shown as free don't add up to [he 664 available on a fresh diskette,
COLLECT is needed (with one exception below.) Similarly. any time a diskette contains an improperly-closed tile (splat file), indicated by an asterisk (*) next to its file type in the directory, that diskette needs to be collected. In fact, but for the one exception below, it is a good idea to COLLECT diskettes whenever you are the least bit concerned about their integrity. Just note the number of blocks free in the diskette's directory before and after using COLLECT, and if the totals differ, there was indeed a problem, and the diskette should probably be copied onto a fresh diskette file by file, using the COpy command described in the previous section, rather than using a backup command or program.
The exception is diskettes containing Direct Access files, as described in Chapter 7.
Most direct access (random) files do not allocate their sectors in a way COLLECT can recognize. Thus, collecting such a diskette may result in un-allocating all direct access files, with loss of all their contents when other files are added. Unless specifically instructed otherwise, never collect a diskette containing direct access files. (Note: these are not the same as the relative files described in Chapter 6. COLLECT may be used on relative files without difficulty.)
FORMAT FOR THE COLLECT COMMAND
COLLECT
The alternate command is:
PRINT# 15. "VALIDATE" or abbreviated to:
PRINT# 15, "V"
INITIALIZE
One command that should not often be needed on the 1551, but is still of occasional value is INITIALIZE. On the 1551, and nearly all other Commodore drives, this function is performed automatically, whenever a new diskette is inserted. (The optical writeprotect 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 DOS, is a re-reading of the current diskette's BAM (Block Availability Map). This information must always be correct in order for the disk to store new files properly.
However, since the chore is handled automatically, the only times you'd need to use the command is if something happened to make the information in the drive buffers unreliable or when an error condition prevents you from performing some operation you want to do.
The INITIALIZE command returns the disk drive to the same state as when it was powered up.
28
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.
FORMAT FOR THE INITIALIZE COMMAND
PRINT # 15, "INITIALIZEdrive#"
PRINT # 15, ,. INITIALIZEO" or it may be abbreviated to
PRINT#15,"Idrive #"
PRINT# 15, "10" where the command channel is assumed to be opened by file 15, and "drive #" is 0 on the 1551.
One use for INITIALIZE is to keep a cleaning diskette spinning, if you choose to use one (under normal conditions, a cleaning diskette is not necessary), If you are using such a kit, the following short program will keep the diskette spinning long enough for your need
(about 20 seconds):
10 OPENI5,8,15
20 FOR 1= I TO 99
30 : PRINT#15,"IO"
40 NEXT
50 CLOSEI5
29
PART TWO: GUIDE TO ADVANCED
OPERATION AND PROGRAMMING
CHAPTER 4
SEQUENTIAL DATA FILES
THE CONCEPT OF FILES
A file on a diskette is just like a file cabinet in your office-an organized place to put things. Nearly everything you put on a diskette goes in one kind of file or another. So far all we've used are program files, but there are others, as we have mentioned. In this chapter we will learn about sequential data files.
As we just suggested, the primary purpose of a data file is to store the contents of program variables, so they won't be lost when the program ends. A sequential data file is one in which the contents of the variables are stored "in sequence," one right after another, just as each link in a chain follows the previous link. You may already be familiar with sequential files from using a DATASSETTE™, because sequential files on diskette are just like the data files used on cassettes. Whether on cassette or diskette, sequential files must be read from beginning to end, without skipping around in the middle.
When sequential files are created, information (data) is transferred byte by byte, through a buffer, onto the magnetic media. Once in the disk drive, program files, sequential data files, and user files all work sequentially. Even the directory acts like a sequential file.
To use sequential files properly, we will learn some more Basic words in the next few pages. Then we'll put them together in a simple but useful program.
Note: Besides sequential data files, two other file types are recorded sequentially on a diskette, and may be considered varying forms of sequential files. They are program files, and user files. When you save a program on a diskette, it is saved in order from beginning to end, just like the information in a sequential data file. The main difference is in the commands you use to access it. User tiles are even more similar to sequential data files--differing, for most purposes, in name only. User files are almost never used, but like program tiles, they could be treated as though they were sequential data files and are accessed with the same commands.
For the advanced user, the similarity of the various file types offers the possibility of such advanced tricks as reading a program file into the computer a byte (character) at a time and rewriting it to the diskette in a modified form. The idea of using one program to write another is powerful, and available on the
Commodore disk drives.
31
OPENING A FILE
One of the most powerful tools in Commodore Basic is the Open statement. With it, you may send almost any data almost anywhere, much like a telephone switchboard that can connect any caller to any destination. As you might expect, a command that can do this much is fairly complex. You have already used Open statements regularly in some of your diskette housekeeping commands.
Before we study the format of the Open statement, let's review some of the possible devices in a Commodore computer system:
Device #: Name:
0
I
Keyboard
DATASSETIE "
2 RS232
3 Screen
4,5 Printer
8,9 Disk drive
Used for:
Receiving input from the computer operator
Sending and receiving information from cassette
Sending and receiving information from a Modem
Sending output to a video display
Sending output to a hard copy printer
Sending and receiving information from diskette
Because of the flexibility of the Open statement, it is possible for a single program statement to contact anyone of these devices, or even others, depending on the value of a single character in the command. Often an Open statement is the only difference between a program that uses a DA T ASSETTE ™ and one using the 1551. If the character is kept in a variable, the device used can even change each time that part of the program is used, sending data alternately and with equal ease to diskette, cassette, printer and screen. r---
REMEMBER TO CHECK FOR DISK ERRORS!
In the last chapter we learned how to check for disk errors after disk commands in a program. It is equally important to check for disk errors after using filehandling statements. Failure to detect a disk error before using another filehandling statement could cause loss of data, and failure of the Basic program.
The easiest way to check the disk is to follow all file-handling statements with a Gosub statement to an error check subroutine.
EXAMPLE:
840 OPEN 4,8,4,"0:DEGREE DAY DATA,S,W"
850 GOSUB 59990:REM CHECK FOR DISK ERRORS
32
FORMAT FOR THE DISK OPEN STATEMENT:
OPEN file #, device #, channel #, "drive #:file name,file type,direction" where:
"file #" is an integer (whole number) between I and 255. If the file number is greater than 127, a line-feed character is inserted after each carriage return in the file opened. Though this may be helpful in printer files, it will cause severe problems in disk files, and is to be avoided at all costs. Do not open a disk file with a file number greater than 127. After the file is open, all other file commands will refer to it by the number given here. Only one file can use any given file number at a time.
"device #" is the number, or primary address, of the device to be used. This number is an integer in the range 0-31 , and is normally 8 on the 1551.
"channel #" is a secondary address, giving further instructions to the selected device about how further commands are to be obeyed. In disk files, the channel number selects a particular channel along which communications for this file can take place. The possible range of disk channel numbers is 0-15, but 0 is reserved for program Loads, I for program Saves, and 15 for the disk command channel. Also be sure that no two disk files have the same channel number unless they will never be open at the same time. (One way to do this is to make the channel number for each file the same as its file number.)
"drive #" is the drive number, always 0 on the 1551. Do not omit it, or you will only be able to use two channels at the same time instead of the normal maximum of three.
If any pre-existing file of the same name is to be replaced, precede the drive number with the "at" sign (@) to request Open-with-replace.
"file name" is the file name, maximum length 16 characters. Pattern matching characters are allowed in the name when accessing existing files, but not when creating new ones.
"file type" is the file type desired: S = sequential. P = program, U = user, and
L = length of a relative file.
"direction" is the type of access desired. There arc three possibilities: R = read,
W=write, and M=modify. When creating a file, use "WOO to write the data to diskette.
When viewing a completed file, use "R" to read the data from diskette. Only usc the
"M" (modify) option as a last ditch way ofreading 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, as such files always include some erroneous data, and have no proper end.)
"file type" and "direction" 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 must be a valid string literal, variable or expression.
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.
33
EXAMPLES OF OPENING SEQUENTIAL FILES:
To create a sequential file of phone numbers, you could usc:
OPEN 2,8,2, "O:PHONES .SEQUENTIAL, WRITE" or save yourself some typing with:
OPEN 2,8,2,"0:PHONES,S,W"
On the off-chance we've already got a "PHONES" file on our diskette. we can avoid a
"FILE EXISTS" error mcssage by doing an (II OPEN
OPEN 2,8,2,"@O:PHONES,S,W"
Of course, this erases all our old phone numbers, so make sure that any information that may be deleted is of no importance. After writing our phone file, we remove our diskette and tum off the system. Later, to recall the data in the file, we would reopen it with something like
OPEN 8,8,8, "O:PHONES ,S,R"
It doesn't matter whether the file and channel numbers match the ones we used before, but the file name does have to match. However, it is possible to usc an abbreviation form of the file name, if there are no other files that would have the same abbreviation:
OPEN 10,8,6, "O:PH* ,S.R"
If we have too many phone numbers, they might not fit in one file. In that case, we might use several similar file names, and let a program choose the correct file.
100 INPUT "WHICH PHONE FILE (l-3)";PH
110 IF PH<>I AND PH<>2 AND PH<>3 THEN 100
120 OPEN 4,8,2:'PHONE" + STR$(PH) + .. ,S,R"
You can omit the drive number on an Open command to read a file. Doing so allows those with dual drives to search both diskettes for the file.
ADDING TO A SEQUENTIAL FILE
The Append command allows you to reopen an existing sequential file and add more information to the end of it. In place of the "type" and "direction" parameters in 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.
34
FORMA T FOR THE APPEND OPTION
OPEN file # ,device #,channeI #, "drive #:file name,A" where everything is as on the previous page except for the ending" A" replacing the
"type" and "direction" parameters.
EXAMPLE:
If you are writing a grading program, it would be convenient to simply tack on each student's new grades to the end of their existing grade liles. To add data to the "JOHN
PAUL JONES" file, we could type
OPEN J,8,3,"O:JOHN PAUL JONES,A"
In this case, DOS will allocate at least one more sector (block) to the file the first time you append to it, even if you only add one character of information. You may also notice that using the Collect or Validate command didn't correct the file size. On the other hand, your data is quite safe, and if the wasted space becomes a problem, you can easily 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 original name, for ease of continued use:
RENAME "JOHN PAUL JONES" TO "TEMP"
COPY "TEMP" TO "JOHN PAUL JONES"
SCRATCH "TEMP"
WRITING FILE DATA: USING PRINT#
After a sequential file has been opened to write (with a type and direction of
",S, W"), we use the Print# command to send data to it for storage on diskette. If you are familiar with Basic's Print statement, you will lind Print# works exactly the same way, except that the list of items following the command word is sent to a particular tile, instead of automatically appearing on the screen. Even the formatting options (punctuation and such) work in much the same way as in Print statements, This means you have to be sure the items sent make sense to the particular file and device used.
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
(typically at the next column whose number is evenly divisible by 10). If the same comma is included between variables going to a disk file, it will again act as a separator, again inserting extra spaces into the data. This time, however, it is inappropriate, as the extra spaces are simply wasted on the diskette, and may create more problems when reading the file back into the computer. Therefore, you are urged to follow the following format precisely when sending data to a disk file.
35
FORMAT FOR THE PRINT# COMMAND:
PRINT#file # ,data list where "file #" is the same file number given in the desired file's current Open statement.
During any given access of a particular file, the file number must remain constant because it serves as a shorthand way of relating all other file-handling commands back to the correct Open statement. Given a file number, the computer can look up everything else about a file that matters.
The "data list" is the same as for a Print statement - a list of constants, variables and/or expressions, including numbers, strings or both. However, it is strongly recommended that each Print# statement to disk include only one data item. If you wish to include more items, they must be separated by a carriage return character, not a comma.
Semicolons are permitted, but not recorded in the file, and do not result in any added spaces in the file. Use them to separate items in the list that might otherwise be confused, such as a string variable immediately following a numeric variable.
Note: Do not leave a space between PRINT and #, and do not abbreviate the command as '1#. The correct abbreviation for Print# is pRo
EXAMPLES:
To record a few grades for John Paul Jones, using a sequential disk file # I previously opened for writing, we could use:
200 FOR CLASS = 1 TO COURSES
210 PRINT#l,GRADE$(CLASS)
220 NEXT CLASS
320 GOSUB 59990:REM CHECK FOR DISK ERRORS
(assuming your program includes an error check subroutine like the one in the last chapter).
In using Print# there is an exception to the requirement to check for disk errors after every file-handling statement. When using Print #, a single check after an entire set of data has been written will still detect the error, so long as the check is made before any other file-handling statement or disk command is used. You may be familiar with Print statements in which several items follow each other:
400 PRINT NAME$,STREET$,CITY$
To get those same variables onto sequential disk file number 5 instead of the screen, the best approach would be to use three separate Print# statements, as follows:
36
400 PRINT#5,NAME$
410 PRINT#5,STREET$
420 PRINT#5,ClTY$
However, if you need to combine them, here is a safe way to do it:
400 PRINT#5,NAME$;CHR$(13);STREET$;CHR$(13);CITY$
CHR$(I3) is the carriage return character, and has the same effect as putting the print items in separate lines. If you do this often, some space and time may be saved by previously defining a variable as equal to CHR$(I3):
10 CR$=CHR$(13) ... 400 PRINT#5,NAME$;CR$;STREET$;CR$;CITY$
The basic idea is that a proper sequential disk file write, if redirected to the screen, will display only one data item per line, with each succeeding item on the next line.
CLOSING A FILE WHEN YOU ARE DONE USING IT
After you finish using a data file, it is extremely important that you Close it. During the process of writing a tile, data is accumulated in a memory buffer. and only written out to the diskette when the buffer Illls.
Working this way, there is almost al ways a small amount of data in the buffer that has not been written to diskette yet, and which would simply be lost if the computer system were turned off. Similarly, there are diskette housekeeping matters, such 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 Ille. This is the reason for having a
Close statement. When we know we are done with a Ille, the Close statement will write the rest of the data buffer out to diskette, update the BAM, and complete the tile's entry in the directory. Always Close a data file when you are done using it! Failure to do so may cause loss of the entire 11 Ie !
However, do not close the disk command channel until all other files have been
Closed. The command channcl (described in the last chapter), when used, should be the first tile Opened, and the last file Closed in any program. Otherwise, remaining files may 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.
FORMAT FOR THE CLOSE STATEMENT
CLOSE file # where "file #" is the same tile number given in the desired file's current Open statement.
EXAMPLES:
To close the data file #5 used as an example on the previous page, we would use
CLOSE 5
37
In Commodore's CBM and PET computers, there is a Dclose statement, that, when used alone, closes all disk files at once. With a bit of planning, the same can be done via a program loop. Since there is no harm in closing a file that wasn't open, close every file you even think might be open before ending a program. If for example, we always gave our files numbers between \ and 5, we could close them all with
9950 FOR 1= \ TO 5
9960 CLOSE I
9970 GOSUB 59990:REM CHECK FOR DISK ERRORS
9980 NEXT I
(assuming your program includes an error check subroutine like the one
In the last
Chapter)
READING FILE DATA: USING INPUT#
Once information has been written properly to a diskette file, it may be read back into 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 command word comes from a particular file instead of the keyboard. Both statements are subject to the same limitations-halting input after a comma or colon, not accepting data items too large to fit in Basic's Input buffer, and not accepting non-numeric data into a numeric variable.
FORMAT FOR THE INPUT# STATEMENT
PRINT#file #, variable list 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 element is to be input by a particular Input# statement, each variable name must be separated from others by a comma.
EXAMPLES:
To read back in the grades written with the Print# example, use:
300 FOR CLASS = \ TO COURSES
3\0 INPUT#\ ,GRADE$(CLASS)
320 GOSUB 59990:REM CHECK FOR DISK ERRORS
330 NEXT CLASS
(assuming your program includes an error check subroutine like the one in the last chapter).
To read back in the address data written by another Print# example, it is safest to use:
38
800INPUT#5,NAME$
810 GOSUB 59990:REM CHECK FOR DISK ERRORS
820INPUT#5,STREET$
830 GOSUB 59990:REM CHECK FOR DISK ERRORS
840INPUT#5,CITY$
850 GOSUB 59990:REM CHECK FOR DISK ERRORS but many programs cheat on safety a bit and use
800INPUT#5,NAME$,STREET$,CITY$
810 GOSUB 59990:REM CHECK FOR DISK ERRORS
This is done primarily when top speed in the program is essential, and there is little or no risk of reading improper data from the file.
MORE ABOUT INPUT# (FOR ADVANCED USERS)
TROUBLESOME CHARACTERS
After you begin using data files regularly, you may encounter two Basic error messages more or less frequently. They are "STRING TOO LONG ERROR" and "FILE
DAT A 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.
"STRING TOO LONG" ERRORS
A Basic string may be up to 255 characters long, although the longest string you can enter via a single Input statement is just under 2 lines of text. This lower limitation is due to the 88 character size of the Input buffer in Commodore's serial bus 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 characters, Basic will halt with a "STRING TOO LONG ERROR". To prevent this 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.)
"FILE DATA" ERRORS
The other error message "FILE DATA ERROR" is caused by attempting to read a non-numeric character into a numeric variable. To a computer, a number is the characters o through 9, the"'
+" and" - " signs, the decimal point (.), the SPACE character, and the letter "E" used in scientific notation. If any other character appears in an Input# to a numeric variable, "FILE DATA ERROR" will be displayed and the program will halt.
The usual causes of this error are a mismatch between the order in which variables are written to and read from a file, a missing carriage return within a Print# statement that writes more than one data item, or a data item that includes either a comma or a colon without a preceding quotation mark. Once a file data error has occurred, you should correct it by reading the data item into a string variable, and then converting it back to a number with the Basic ValO statement after removing non-numeric characters with the string functions described in your computer users manual.
39
COMMAS (,) AND COLONS (:)
As suggested before, commas and colons can cause trouble in a file, because they delimit (end) the data element in which they appear and cause any remaining characters in the data element to be read into the next Input# variable. (They have the same effect in an
Input statement, causing the common "EXTRA IGNORED" error message.) However, sometimes we really need a comma or colon within a data element, such as a name written as "Last, First". The cure is to precede such data elements with a quotation mark. After a 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.
EXAMPLES:
To force a quotation mark into a data element going to a file, append a CHR$(34) to the start of the data element. For example:
PRINT#2,CHR$(34)
+
"GUNGA DIN" or
PRINT#2,CHR$(34);"GUNGA DIN"
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):
20 QT$=CHR$(34)
400 PRINT#5,QT$
+
NAME$
In
each case, the added quotation mark will be stripped out of the data by the Input or
Input# statement, but the comma or colon will remain safely part of the data.
NUMERIC DATA STORAGE ON DISKETTE
Inside the computer, the space occupied by a numeric variable depends only on its type. Simple numeric variables use 7 bytes (character locations) of memory. Real array variables use 5 bytes per array element, and integer array elements use 2 bytes each.
In
contrast, when a numeric variable or any type is written to a file, the space it occupies depends entirely on its length, not its type.
Numeric data is written to a file in the form of a string, as if the Str$\) function had been performed on it. The first character will be a blank space if the number is positive, and a minus sign (-) if the number is negative. Then comes the number, digit by digit.
The last character is a cursor right character.
This format allows the disk data to be read back into a string or numeric variable later. It is, however, somewhat wasteful of disk space, and it can be difficult to anticipate the space required by numbers of unknown length. For this reason, some programs
40
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 elements to be read back into a numeric variable by Input# later, although file data errors may be avoided by reading all data in as strings, and converting to numbers after the information is inside the computer.
For example, "N$=RIGHT$(STR$(N),LEN(STR$(N»-I)" will convert a positive number N into a string N$ without the usual leading space for its numeric sign. Then instead of writing PRINT#5,N, you would use PRINT#5,N$.
READING FILE DATA: USING GET#
The Get# statement retrieves data from the disk drive, one character at a time. Like 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 next statement if there is no data to be gotten. The primary use of Get# is to retrieve from diskette any data that cannot be read into an Input# statement, either because it is too long to fit in the input buffer or because it includes troublesome characters.
FORMAT FOR THE GET# STATEMENT:
GET#file#, variable list 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 element is to be input by a particular Get# statement, each variable name must be separated from others by a comma.
In practice, you will almost never see a Get or Get# statement containing more than one variable name. If more than one character is needed, a loop is used rather 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.
Data in a Get# statement comes in byte by byte, including such normally invisible characters as the Carriage Return, and the various cursor controls. All but one will be read properly. The exception is CHR$(O), the ASCII Null character. It is different from an empty string (one of the form A$ = ''''), even though empty strings are often referred to as null strings. Unfortunately, in a Get# statement, CHR$(O) is converted into an empty string. The cure is to test for an empty string after a Get#, and replace any that are found with CHR$(O) instead. The first example below illustrates the method.
EXAMPLES:
To read a file that may contain a CHR$(O), such as a machine language program file, we could correct any CHR$(O) bytes with
1\00 GET#3,G$:IF G$="" THEN G$=CHR$(O)
41
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
3300 B$= ""
3310 GET#I,A$
3320 IF A$<>CHR$(13) THEN B$ = B$ + A$:GOTO 3310
The limit for such a technique is 255 characters. It will ignore CHR$(O), but that may be an advantage in building a text string.
Get# may be especially useful in recovering damaged files, or files with unknown contents. The Basic reserved variable ST (the file STatus variable) can be used to indicate when all of a properly-closed file has been read.
500 GET#2,S$
510 SU=ST:REM REMEMBER FILE STATUS
520 PRINT S$;
530 IF SU =0 THEN 500:REM IF THERE'S MORE TO BE READ
540 IF SU<>64 THEN PRINT "STATUS ERROR: ST = ";SU
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 loops back to read again. For example, it would be required if line 520 was changed to
520 PRINT# 1 ,S$;
Otherwise, the file status checked in line 530 would be that of the write file, not the read file.
IFST= o
1
2
4
8
16
32
64
128
POSSIBLE VALUES OF THE FILE STATUS VARIABLE "ST",
AND THEIR MEANINGS
THEN
All is OK
Receiving device was not available (time out on talker)
Transmitting device was not available (time out on listener)
Cassette data file block was too short
Cassette data file block was too long
Unrecoverable read error from cassette, verify error
Cassette checksum error--one or more faulty characters were read
End of file reached (EQ[ detected)
Device not present, or end of tape mark found on cassette
42
DEMONSTRATION OF SEQUENTIAL FILES
Use the following program for your first experiments with sequential files.
Comments have been added to help you better understand it.
150 CR$ = CHR$(13)
160 OPEN 15,8,15
170 PRINT CHR$(l47):REM CLEAR
SCREEN
190 PRINT
,,**
WRITE A FILE
**"
210 PRINT
220 OPEN 2,8,2,' '@O:SEQ FILE,S, W"
230 GOSUB 500
240 PRINT"ENTER A WORD,
THEN A NUMBER"
250 PRINT"OR 'END,O' TO STOP"
260 PRINT
270 INPUT A$,B
280 PRINT#2,A$;CR$;B
290 GOSUB 500
300 IF A$<>"END" THEN 270
3IO PRINT
320 CLOSE 2
340 PRINT
"**
READ SAME FILE
BACK
**"
360 PRINT
370 OPEN 2,8,2, "O:SEQ FILE,S,R"
380 GOSUB 500
390INPUT#2,A$,B
400 RS=ST
4IO GOSUB 500
420 PRINT A$,B
430 IF RS = 0 THEN 390
440 IF RS<>64 THEN
PRINT"STATUS = ";RS
450 CLOSE 2
460 END
480 REM
**
ERROR CHECK SIR
**
500INPUT#15,EN,EM$,ET,ES
5 IO IF EN>O THEN PRINT
EN,EM$,ET,ES:STOP
520 RETURN
Make a carriage return variable
Open demo file with replace
Check for disk errors
Accept a string & number from keyboard
Write them to the disk file
Until finished
Tidy up
Reopen same tile for reading
Read next string & number from file
Remember file status
Display file contents until done, unless there's an error
Then quit
A Basic 3.5-only version could replace line 500 with
500 IF DS>O THEN PRINT
DS$:STOP and delete line 5 IO
43
CHAPTERS
RELA TIVE FILES
THE VALUE OF RELATIVE ACCESS
Sequential files are very useful when you're just working with a continuous stream of data -- i.e., information that can be read or written all at once. However, sequential files are not useful or desirable in some situations. For example, after writing a large list of mail labels, you wouldn't want to have to re-read the entire list each time you need a person's record. Instead, you need some kind of random access, a way to get to a particular label in your file without having to read through all those preceding it first.
As an example, compare a record turntable with a cassette recorder. You have to listen to a cassette from beginning to end, but a turntable needle can be picked up at any time, and instantly moved to any spot on the record. Your disk drive works like a turntable in that respect. In this chapter we will learn about a type of file that reflects this flexibility.
Actually, two different types of random access files may be used on Commodore disk drives: relative files and random files. Relative files are much more convenient for most data handling operations, but true random access file commands are also available to advanced users, and will be discussed in the next chapter.
}<'ILES, RECORDS, AND FIELDS
When learning about sequential files, we did not worry about the organization of data within a file, so long as the variables used to write the file matched up properly with those which read it back into the computer. But in order for relative access to work, we need a more structured and predictable environment for our data.
The structure we will use is similar to that used in the traditional filing cabinet. In a traditional office, all customer records might be kept in a single file cabinet. Within this file, each customer has a personal record in a file folder with their name on it, that contains everything the office knows about that person. Likewise, within each file folder, there may be many small slips of paper, each containing one bit of information about that customer, such as a home phone number, or the date of the most recent purchase.
In a computerized office, the file cabinet is gone, but the concept of a file containing all the information about a group or topic remains. The file folders are gone too, but the notion of subdividing the file into individual records remains. The slips of paper within the personal records are gone too, replaced by subdivisions within the records, called fields. Each field is large enough to hold one piece of information about one record in the file. Thus, within each file there are many records, and within each record there are typically many fields.
A relative file takes care of organizing the records for you, numbering them from I to whatever, by ones, but the fields are up to you to organize. Each record will be of the same size, but the 1551 won't insist that they all be divided the same way. On the other hand, they normally will all be subdivided the same way, and if it can be known in
44
advance exactly where each field starts within each record, there are even fast ways to 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 desired person out of a thousand in under 15 seconds, a feat no sequential file program could match.
FILE LIMITS
One of the nicest aspects of relative files is that all this is done for you without your having to worry at all about exactly where on the diskette's surface a given record will be stored, or whether it will fit properly within the current disk sector, or need to be extended onto the next available sector. DOS takes care of all that for you. All you need to do is specify how long each record is, in bytes, and how many records you will need. DOS will do the rest, and organize things in such a way that it can quickly find any record in the file, as soon as it is given its record number (ordinal position within the file).
The only limit that will concern you, is that each record must be the same size, and the record length you choose must be between 2 and 254 characters. Naturally the entire file also has to fit on your diskette too, which means that the more records you need, the shorter each must be.
CREATING A RELATIVE FILE
When a relative file is to be used for the first time, its Open statement will create the file; after that, the Open statement can be used to re-open the file for both reading and writing.
FORMAT STATEMENT TO OPEN A RELATIVE FILE:
OPEN file #, device #, channel #, "drive #: file name, L," length)
+ CHR$ (record where "file #" is the file numb.:r, normally an integer between I and 127; "device #" is the device number to be used, normally 8 on the 1551; "channel #" selects a particular channel along which communications for this file can take place, normally between 2 and
14; "drive #" is the drive number, always 0 on the 1551; and "file name" is the file name, with a maximum length of 16 characters. Pattern matching characters are allowed in the name when accessing an existing file, but not when creating a new one. The
"record length" is the size of each record within the file in bytes used, including carriage returns, quotation marks and other special characters.
45
Notes:
I. Do not precede the drive number with the "at" sign (@); there is no reason to replace a relative file.
2. ,L ," + CHR$(record length) is only required when a relative file is first created, though it may used later, so long as the "record length" is the same as when the file was first created. Since relative files may be read from or written to alternately and with equal ease, there is no need to specify Read or Write mode when opening a relative file.
3. "tile #", "device #" and "channel #" must be valid numeric constants, variables or expressions. The rest of the command must be a valid string literal, variable or expression.
4. Only I relative file can be open at a time on the 1551, although a sequential file and the command channel may also be open at the same time.
EXAMPLES:
To create or re-open a relative ftle named "GRADES", of record length I 00, use
OPEN 2,8,2."GRADES,L," +CHR$(lOO)
To re-open an unknown relative file of the user's choice that has already been created, we could use
200 INPUT"WHICH FILE":FI$
210 OPEN 5,8,5,FI$
USING RELATIVE FILES: RECORD# COMMAND
When a relative file is opened for the first time, it is not quite ready for use. Both to save time when using the file later, and to assure that the file will work reliably, it is necessary to create several records before closing the file for the first time. At a minimum, enough records to fill more than 2 disk sectors (512 bytes) should be written. In practice, most programs go ahead and create as many records as the program is eventually expected to use. That approach has the additional benefit of avoiding such problems as running out of room on the diskette before the entire file is completed.
If you simply begin writing data to a just-opened relative file, it will act much like a sequential tile, putting the data clements written by the first Print# statement in Record
# I, those written by the second Print# statement in record #2 and so on. (As this implies, each relative record must be written by a single Print# statement, using embedded carriage returns within the data to separate fields that will be read in via one or more
Input# statements later.) However, it is far better to explicitly specify which record number is desired via a Record# command to the disk. This allows you to access records in any desired order, hopping anywhere in a file with equal ease. Properly used, it also avoids a subtle error (bug) common to all Commodore disk drives.
46
FORMAT FOR THE RECORD# COMMAND:
PRINT#15, "P" +CHR$ (channel # +96) +CHR$ «record #) + CHR$
(>record #)+CHR$ (offset) 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 two byte integer, ">record #" is the high byte of the desired record number, and an optional "offset" value, if present, is the byte within the record at which a following
Read or Write should begin.
To fully understand this command, we must understand how most integers are stored 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
I byte holding the part of the number that is evenly divisible by 256, and any remainder in the other byte. In machine language, such numbers are written backwards, with the loworder byte (the remainder) first, followed by the high order byte. In assembly language programs written with the Commodore Assembler, the low part of a two byte number is indicated by preceding its label with the less-than character «). Similarly, the high part of the number is indicated by greater-than (».
SAFETY NOTE: GIVE EACH RECORD# COMMAND TWICE!
To avoid the remote possibility of corrupting relative file data, it is necessary to give Record# commands twice--once before a record is read or written, and again immediately afterwards.
EXAMPLES:
To position the record pointer for file number 2 to record number 3, we could type:
PRINT #15, "P" +CHR$ (98) +CHR$ (3) +CHR$ (0)
The CHR$(98) comes from adding the constant (96) to the desired channel number (2).
(96 + 2 = 98) Although the command appears to work even when 96 is not added to the channel number, the constant is normally added to maintain compatibility with the way
Record# works on Commodore's CBM and PET computers.
Since 3 is less than 256, the high byte of it~ binary representation is 0, and the entire value fits into the low byte. Since we want to read or write from the beginning of the record, no offset value is needed.
Since these calculations quickly become tedious, most programs are written to do them for you. Here is an example of a program which inputs a record number and converts it into the required low bytelhigh byte form:
47
450 INPUT"RECORD # DESIRED";RE
460 IF RE< lOR RE>65535 THEN 450
470 RH = INT(RE/256)
480 RL= RE-256*RH
490 PRINT#15, "P" +CHR$ (98) +CHR$ (RL) +CHR$ (RH)
Assuming RH and RL are calculated as in the previous example, programs may also use variables for the channel, record, and offset required:
570 INPUT "CHANNEL, RECORD, & OFFSET DESIRED";CH,RE,OF
630 PRINT# 15, "P" + CHR$ (CH + 96) + CHR$ (RL) + CHR$ (RH) + CHR$ (OF)
ANOTHER RECORD# COMMAND
Basic 4.0 on Commodore's PET and CBM models includes a Basic Record# command not found in any of the serial bus computers. However, some available utility programs for these models include it. It serves the same function as the
Record# command explained above, but has a simplified syntax:
RECORD#file # ,record # ,offset where "file #" is the relative file number being used, not the command channel's file, "record #" is the desired record number, and "offset" is as above.
If you see a Record# command written in Basic 4 form in a program you want to use, simply convert it into the usual form for both Basic 2 and 3.5 described in this section.
COMPLETING RELATIVE FILE CREATION
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 that CHR$(255) is a special character in a relative file. It is the character used by the DOS to fill relative records as they are created, before a program fills them with other information. Thus, if we want to write the last record we expect to need in our file with dummy data that will not interfere with our later work, CHR$(255) is the obvious choice.
Here is how it works in an actual program which you may copy for use in your own relative file programs.
1020 OPEN 15,8,15
1380 INPUT"ENTER RELATIVE FILE NAME";FI$
1390 INPUT"ENTER MAX. # OF RECORDS";NR
1400 INPUT"ENTER RECORD LENGTH";RL
Open command channel
Select file parameters
48
1410 OPEN 1,8,2, "0:" + FI$+" ,L," +CHR$(RL)
1420 GOSUB 59990
1430
RH
= INT(NRl256)
1440 RL=NR-256*RH
1450 PRINT# 15, 'P' + CHR$(96 + 2) +
CHR$(RL) + CHR$(RH)
1460 GOSUB 59990
1470 PRINT#1 ,CHR$(255);
1480 GOSUB 59990
1490 PRINT#15,'P' + CHR$(96 + 2)+
CHR$(RL) + CHR$(RH)
1500 GOSUB 59990
1510 CLOSE 1
1520 GOSUB 59990
9980 CLOSE 15
9990 END
59980 REM CHECK DISK SUBROUTINE
59990INPUT#15,EN,EM$,ET,ES
60000 IF EN>1 AND EN<>50 THEN PRINT
EN ,EM$,ET ,ES:STOP
600 10 RETURN
Begin to create desired file
Check for disk errors
Calculate length values
Position to last record number
Send default character to it
Re-position for safety
Now the file can be safely closed
And the command channel closed
Before we end the program
Error check subroutine
Ignore "RECORD NOT
PRESENT"
Two lines require additional explanation. When line 1470 executes, the disk drive will operate for up to ten or more minutes, creating all the records in the file, up to the maximum record number you selected in line 1390. This is normal, and only needs to be 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, line 60000 above is different from the equivalent line in the error check subroutine given earlier. Here disk error number 50 is specifically ignored, because it will be generated when the error channel is checked in line 1460. We ignore it because not having a requested record would only be an error if that record had previously been created.
EXPANDING A RELATIVE FILE
What if you underestimate your needs and need to expand a relative file later? No 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 information in it, and also automatically create any other missing records below it in number. The only penalty will be a slight time delay while the records are created.
49
WRITING RELATIVE FILE DATA
The commands used to read and write relative file data are the same Print#, Input#, and Get# commands used in the preceding chapter on Sequential files. Each command is used as described there. However, some aspects of relative file access do differ from sequential fIle programming. and we will cover those differences here.
DESIGNING A RELATIVE RECORD
As stated earlier in this chapter, each relative record has a fixed length, including all special characters. Within that fixed length, there are two popular ways to organize various individual fields of information. One is free-format, with individual fields varying in length from record to record. and each field separated from the next by a carriage return character (each of which does take up I character space in the record). The other approach is to use fixed-length fields, that mayor may not be separated by carriage returns. If fixed length fields are not all separated by carriage returns, you will either need to be sure a carriage return is included within each 88 character portion of the record. If this is not done. you will have to use the Get# command to read the record, at a significant cost in speed.
Relative records of 88 or fewer characters, or final portions of records that are 88 or fewer characters in length, need not end in a carriage return. The 1551 is smart enough to recognize the end of a relative record even without a final carriage return. Though the saving of a single character isn't much, when multiplied by the number of records on a diskette, the savings could be significant.
Since each relative record must be written by a single Print# statement, the recommended approach is to build a copy of the current record in memory before writing it to disk. It can be collected into a single string variable with the help of Basic's many stringhandling functions, and then all written out at once from that variable.
Here is an example. If we are writing a 4-line mail label, consisting of 4 fields named
"NAME", "STREET", "CITY & STATE", and "ZIP CODE", and have a total record size of 87 characters, we can organize it in either of two ways:
WITH FIXED LENGTH FIELDS
Ficld Name Length
NAME
STREET
27 characters
27 characters
CITY & STATE 23 characters
ZIP CODE 10 characters
Total length 87 characters
WITH VARIABLE LENGTH FIELDS
Field Name Length
NAME
STREET
31 characters
3 1 characters
CITY & STATE 26 characters
ZIP CODE 11 characters
Potential length
Edited length
99 characters
87 characters
With fixed length records, the field lengths add up to exactly the record length. Since the total length is just within the Input buffer size limitation, no carriage return characters are needed. With variable length records, we can take advantage of the variability of actual address lengths. While one name contains 27 letters, another may have only 15,
50
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 between maximum field length and average field length. A program that uses variable record lengths must calculate the total length of each record as it is entered. to be sure the total of all fields doesn't exceed the space available.
WRITING THE RECORD
Here is an example of program lines to enter variable length fields for the above tile design, build them into a single string. and send them to record number RE in lile number
3 (assumed to be a relative file that uses channel number 3).
100 INPUT"ENTER RECORD NUMBER";RE
IIOOPENI5.8.15
120 OPEN3.8.3."MYRELFILE,L." +CHR$(8S)
130 CR$
=
CHR$( 13)
140 INPUT"'NAME"; NA$
150 IF LEN(A$»30 THEN 140
160INPUrSTREET";SA$
170 IF LEN(SA$»30 THEN 160
180 INPUT"CITY & STATE"; CS$
190 IF LEN(CS$»25 THEN ISO
200 INPUT"ZIP CODE";ZP$
210 IF LEN(ZP$» 10 THEN 200
220 DA$ = NA$ + CR$ + SA$ + CR$ + CS$
+CR$+ZP$
230 IFLEN(DA$)<88 THEN 260
240 PRINT"'RECORD TOO LONG"
250 GOTOl40
260 RH = INT(RE/256)
270 RL = RE - 256*RH
280 PRINT#15,"P" +CHR$(96+ 3) +CHR$(RL)
+ CHR$(RH) + CHR$( I)
290 IFDS
=
50THENPRINT#3,CHR$(255):
GOS UB 1000:GOT0280
300 GOSUBIOOO
310 PRINT#3,DA$
320 GOSUBIOOO
330 PRINT#15. "p" + CHR$(96 + 3) +CHR$(RL)
+ CHR$(RH) + CHR$( I)
340 GOS UB 1000
350 CLOSE3:CLOSEI5:END
1000 IFDS<20 THEN RETURN
1010 PRINTDS$:CLOSE3:CLOSEI5:END
Select record number
Open command channel
Open the relative tile called "myrellile".
Record length is 88.
Enter fields.
Check length of each.
Build output data string and check its length. If too long then try again.
Calculate record number.
Position to Start of Record #.
If record not present then create it by by writing to it. Then reposition.
Send the data and check for errors.
Reposition for safety.
Close and end.
Error checking subroutine.
READY.
51
To use the above program lines for the version with fixed length tields, we would alter a few lines as follows:
10 INPUT"ENTER RECORD NUMBER";RE
200PENIS,8,IS
30 OPEN3,8,3, "MYRELFILE,L," + CHR$(88)
40 BL$ = ""
SO INPUT"NAME";NA$
60 LN = LEN(NA$)
70 IFLEN(NA$»27 THEN SO
80 NA$ = NA$ + LEFT$(BL$,27 - LN)
90INPUT"STREET';SA$
100 LN = LEN(SA$)
110 IF LEN(SA$»27 THEN 90
120 SA$ = SA$ + LEFT$(BL$,27 - LN)
130 INPUT"CITY & STATE";CS$
140 LN = LEN(CS$)
ISO IF LEN(CS$»23 THEN 130
160 CS$ = CS$
+
LEFT$(BL$,23 - LN)
170 INPUT"ZIP CODE" ;ZP$
180 LN = LEN(ZP$)
190 IF LEN(ZP$» 10 THEN 170
200 ZP$
=
ZP$
+
LEFT$(BL$, 10- LN)
210 DA$
=
NA$ + SA$ + CS$ + ZP$
220 RH
=
INT(RE/2S6)
230 RL = RE - 2S6*RH
240 PRINT# IS, "P"
+
CHR$(96
+
3)
+
CHR$(RL)
+
CHR$(RH)
+
CHR$( I)
2S0 IFDS = SOTHENPRINT#3,CHR$(2SS):
GOSUB J 000:GOT0240
260 GOSUB 1000
270 PRINT#3,DA$;
280 GOSUB 1000
290 PRINT# IS, "P"
+
CHR$(96
+
3)
+ CHR$(RL) + CHR$(RH) + CHR$( I)
300 GOSUBlOOO:CLOSE3:CLOSEIS:END
1000 IFDS<20 THEN RETURN
1010 PRINT"ERROR: "DS$:CLOSE3:CLOSEIS:END
Select record number.
Open command channel.
Open the relative file
"myrelfile" , record length is 88.
27 shifted space characters
Enter fields.
Check length of each, padding with shifted spaces to pre-set size.
Build output data string.
Calculate record number.
Position to record number reo
If record not present, then create it by writing to it and reposition.
Send the data and check for errors. Note the added semi-colon.
Close and end.
Error checking subroutine.
READY,
If field contents vary in length, variable field lengths are often preferable. On the other hand, if the field lengths are stable, fixed field lengths arc preferable. Fixed length fields are also required if you want to use the optional offset parameter of the Record# command to point at a particular byte within a record. However, one warning must be made about using the offset this way. When any part of a record is written, DOS
S2
overwrites any remaining spaces in the record. Thus, if you must use the offset option, never update any field in a record other than the last one unless all succeeding fields will also be updated from memory later.
The above programs are careful to match record lengths exactly to the. space available. Programs that don't do so will discover that DOS pads short records out to full size with fill characters, and truncates overlong records to fill only their allotted space.
When a record is truncated, DOS will indicate error 51, "RECORD OVERFLOW", but short records will be accepted without a DOS error messagc.
READING A RELATIVE RECORD
Once a relative record has been written properly to diskette, reading it back into 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 variable fields created above from record number RE in file and channel 3:
10 OPENI5,8,15
20 OPEN3,8,3, "O:MYRELFILE,L," + CHR$(88)
Open the command channel.
Open the relative file
"myrelfile". Record length is 88.
30 INPUT"ENTER RECORD NUMBER";RE
40 RH = INT(RE/256)
50 RL = RE - 256*RH
60 PRINT# 15, "P" + CHR$(96 + 3) +CHR$(RL)
+ CHR$(RH) + CHR$( 1)
70 GOSUBlOOO
80 INPUT#3, NA$,SA$,CS$,ZP$
90 GOSUB1000
100 PRINT#15,"P" +CHR$(96.3) +CHR$(RL)
+ CHR$(RH) + CHR$( I)
110 GOSUB 1000
120 PRINTNA$:PRINTSA$
130 PRINTCS$:PRINTZP$
140 CLOSE3:CLOSEI5:END lOOOIFDS<20THENRETURN
1010 PRINTDS$:CLOSE3:CLOSEI5:END
Select and calculate record number.
Position to start of record # RE and check for errors.
Input the data and check for errors.
Reposition for safety.
Print the record on screen.
Close and end.
Error checking subroutine.
READY.
Here are the lines needed to read back the version with fixed length fields:
10 OPENI5,8,15
20 OPEN3,8,3, "O:MYRELFlLE,L," + CHR$(88)
Open command channel.
Open the relative file called
"myrelfile" The record length is
88.
Select and calculate record #. 30 INPUT"ENTER RECORD NUMBER";RE
40 RH = INT(RE/256)
50 RL=RE-256*RH
53
60 PRINT# 15, "P" + CHR$(96 + 3) + CHR$(RL)
+ CHR(RH) + CHR$(l)
70 GOSUB 1000
80INPUT#3,DA$
90 GOSUBlOOO
100 PRINT#15, "P" +CHR$(96 + 3)+ CHR$(RL)
+ CHR$(RH) + CHR$( I)
110 GOSUB 1000
120 NA$= LEFf$(DA$,27)
130 SA$=MlD$(DA$,28,27)
140 CS$ = MlD$(DA$,55,23)
150 ZP$ = RIGHT$(DA$, 10)
160 PRINTNA$:PRINTSA$
170 PRINTCS$:PRINTZP$
180 CLOSE3:CLOSEI5:END
1000 IFDS<20 THEN RETURN
1010 PRINTDS$:CLOSE3:CLOSEI5:END
Position to start of record
# RE and check for errors.
Input the record.
Reposition for safety.
Split the data into fields.
Print data on screen.
Close and end.
Error checking subroutine.
READY.
THE VALUE OF INDEX FILES (ADVANCED USERS)
In the last two chapters we have learned how to use sequential and relative files separately. But they are often used together, with thc sequential file used to keep brief records of which name in thc rclative file is stored in each record number. That way the contents of the sequential fi Ic can be read into a string array and sorted alphabetically.
After sorting, a techniquc known as a binary search can be used to very quickly find an entered name in the array, and read in or write the associated record in the relative file.
Advanced programs can maintain two or more such index files, sorted in differing ways simultaneously.
54
CHAPTER 6
DIRECT ACCESS COMMANDS
A TOOL FOR ADVANCED USERS
Direct access commands specify individual sectors on the diskette, reading and writing information entirely under your direction. This gives them almost complete flexibility in data-handling programs, but also imposes tremendous responsibilities on the programmer, to be sure nothing goes awry. As a result, they are normally used only in complex commercial programs able to properly organize data without help from the disk drive itself.
A far more common usc of direct access commands is in utility programs used to view and alter parts of the diskette that are not normally seen directly. For instance, such commands can be used to change the name of a diskette without erasing all of its programs, to lock a program so it can't be erased, or hide your name in a location where it won't be expected.
DISKETTE ORGANIZATION
There are a total of 683 blocks on a diskette, of which 664 are available for use, with the rest reserved for the BAM (Block Availability Map) and the Directory.
The diskette's surface is divided into tracks, which are laid out as concentric circles 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
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 room on the outer tracks, there are more sectors per track there. The outermost tracks contain 21 sectors each, while the innermost ones only have 17 sectors each. The table below shows the number of sectors per track.
TRACK NUMBER
Table 6.1: Track and Sector Format
SECTOR NUMBERS TOT AL SECTORS
I to 17
18 to 24
25 to 30
31 to 35 o through 20 o through 18 o through 17 o through 16
21
19
18
17
In this chapter we will describe the DOS commands for directly reading and writing any track and block on the diskette, as well as the commands used to mark blocks as used or unused.
OPENING A DATA CHANNEL FOR DIRECT ACCESS
When working with direct access data, you need two channels open to the disk: the command 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
55
channel is opened much like other files, except that the pound sign (#), optionally followed by a memory buffer number, is used as a file name.
FORMAT FOR DIRECT ACCESS FILE OPEN STATEMENTS:
OPEN file # ,device #. channel #, "#buffer #" where "file #" is the file number, "device #" is the disk's device number, normally 8;
"channel #" is the channel number, a number between 2 and 14 that is not used by other files open at the same time; and "buffer #", if present, is a 0, I, 2, or 3, specifying the memory buffer within the 1551 to use for this file's data.
EXAMPLES:
If we don't specify which disk buffer to use, the 1551 will select one:
OPEN 5,8,5,"#"
Or we can make the ehoice ourselves:
OPEN 4,8,4," #2"
BLOCK-READ
The purpose of a Block Read is to load the contents of a specified sector into a file buffer. Although the Block Read command (B-R) is still part of the DOS command set, it is nearly always replaced by thc U I command (See chapter 9).
FORMAT FOR THE BLOCK-READ COMMAND:
PRINT#15, "Ul"; channel #; drive #: track #; sector # whcre "channel #" is the channel number specified when the file into which the block will be read was opened, "drive #" is the drive number. always
°
on the ISS I. and
"track #" and "sector #" are respectively the track and sector numbers containing the desired block of data to be read into the file buffer.
ALTERNATE FORMATS:
PRlNT#15,"Ul:"channel #;drive #;track #;sector #
PRINT#15,"UA:"ehannel #;drive #;track #;sector #
PRINT#15,"Ul:channel #,drive #,track # ,sector #"
56
EXAMPLE:
Here is a complete program to read a sector into disk memory using U I, and from there 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#).
110 MB = 7936:REM $1 FOO
120 INPUT"TRACK TO READ";T
130 INPUT"SECTOR TO READ";S
140 OPEN 15,8,15
150 OPEN 5,8,5, "#"
160 PRINT#15,"UI";5;0;T;S
170 FOR I = MB TO MB + 255
180 GET#5,A$:IF A$ =" "
THEN A$ = CHR$(O)
190: POKE I,ASC(A$)
200 NEXT
210 CLOSE 5:CLOSE 15
220 END
Define a memory buffer
Select a track and sector
Open command channel
Open direct access channel
Read sector into disk buffer
Use a loop to copy disk buffer into computer memory
Tidy up after
As the loop progresses, the contents of the specified track and sector are copied into 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 "DlSPLA Y T & S" on the
Test/Demo diskette.
BLOCK-WRITE
The purpose of a Block Write is to save the contents of a file buffer into a specified sector. It is thus the reverse of the Block Read command. Although the Block Write command (B-W) is still part of the DOS command set, it is nearly always replaced by the
U2 command.
FORMAT FOR THE BLOCK-WRITE COMMAND:
PRINT#15,"U2";channel #;drive #;track #;sector # where "channel #" is the channel number specified when the file into which the block will be read was opened; "drive #" is the drive number (always 0 on the 1551); and
"track #" and "sector #" are respectively the track and sector numbers that should receive the block of data being saved from the file buffer.
ALTERNATE FORMATS:
PRINT#15,"U2:"channel #;drive #;track #;sector #
PRINT#15,"UB:"channel #;drive #;track #;sector #
PRINT#15,"U2:channel #,drive #,track #,sector #"
57
EXAMPLES:
To restore track 18. sector I of the directory from the disk buffer filled by the Block
Read example on page 82. we can use
PRINT# 15, "U2";5;0; 18; I
We'll return to this example on the next page, after we learn to alter the directory in a useful way.
We can also use a Block Write to write a name in Track I, Sector I. a rarely-used sector. This can be used as a way of marking a diskette as belonging to you. Here is a program to do it. using the alternate form of the Block Write command:
110 INPUT"YOUR NAME";NA$
120 OPEN 15.8,15
130 OPEN 4,8,4,"#"
140 PRINT#4,NA$
150 PRINT#15,"U2";4;O;I;1
160 CLOSE 4
170 CLOSE 15
180 END
Enter a name
Open command channel
Open direct access channel
Write name to buffer
Write buffer to Track
Sector I of diskette
Tidy up after
I,
THE ORIGINAL BLOCK-READ AND BLOCK-WRITE COMMANDS (EXPERT
USERS ONLY)
Although the Block Read and Block Write commands are nearly always replaced by the U I and U2 commands respectively, the original command, can still be used, as long as you fully understand their effects. Unlike UI and U2, B-R and B-W allow you to read 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 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 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 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.
FORMAT FOR THE ORIGINAL BLOCK-READ AND BLOCK-WRITE COM-
MANDS:
PRINT#15,"BLOCK-READ";channel #;drive #;track #:sector # abbreviated as: PRINT#15,"B-R";channel #;drive #;track #;sector #
58
and
PRINT# 15. "BLOCK-WRITE";channel #;drive #;track #;sector # abbreviated as: PRINT# IS, "B- W";channel #;drive #;track #:seetor # where "channel #" is the channel number specified when the fiJc into which the block will be read was opened, "drive #" is the drive number (always () on the 1551). and
"track #" and "sector #" are respectively the track and sector numbers containing the desired block of data to be partially read into or written from the file buffer.
IMPORT ANT NOTES:
1. In a true Block-Read, thc lirst byte of the selected sector is used to 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 always interpreted as being the number of characters to read, rather than part of the data.
2. Similarly, in a true Block-Write. when the buffer is written hack to diskette. the first byte written is the current value of the buffer pointer. and only that many bytes are written into the specified sector. It cannot be used to rewrite an entire sector onto diskette unchanged. because the first data byte is overwritten by the buffer pointer.
THE BUFFER POINTER
The buffer pointer points to where the next Read or Write will begin within a disk memory buffer. By moving the buffer pointer. you can access individual bytes within a block in any order. This allows you to edit any portion of a sector. or organize it into fields. like a relative record.
FORMAT FOR THE BUFFER-POINTER COMMAND:
PRINT# 15. "BUFFER-POINTER" ;channel #:byte usually abbreviated as: PRINT# 15, "B-P";channel #;byte where "channel #" is the channel number specified when the liJc reserving the buffer was opened, and "byte" is the character number within the buffer at which to point.
59
ALTERNATE FORMATS:
PRINT#15, "B-P:"channel #;byte
PRINT#15, "B-P:channel #;byte"
EXAMPLE:
Here is a program that locks the first program or file on a diskette. It works by reading the start of the directory (Track 18, Sector I) into disk memory, setting the buffer pointer to the first file type byte (see Appendix C for details of directory organization), locking it by setting bit 6 and rewriting it.
110 OPEN 15,8,15
120 OPEN 5,8,5,"#"
130 PRINT# 15, "UI ";5;0;18; I
140 PRINT# 15, "B-P";5;2
150 GET#5,A$:IF A$ =" " THEN A$ = CHR$(O)
160 A=ASC(A$) OR 64
170 PRINT#15,"B-P";5;2
180 PRINT#5,CHR$(A);
190 PRINT#15, "U2";5;0;18;1
200 CLOSE 5
210 CLOSE 15
220 END
Open command channel
Open direct access channel
Read Track 18, Sector I
Point to Byte 2 of the buffer
Read it into memory
Turn on bit 6 to lock
Point to Byte 2 again
Overwrite it in buffer
Rewrite buffer to diskette
Tidy up after
After the above program is run, the first file on that diskette can no longer be erased. If you later need to erase that file, re-run the same program, but substitute the revised line
160 below to unlock the file again:
160 A=ASC(A$) AND 191 Turn off bit 6 to unlock
ALLOCATING BLOCKS
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 other files from being written there. Blocks thus" allocated" will be safe until the diskette is validated.
FORMAT FOR BLOCK-ALLOCATE COMMAND:
PRINT#15, "BLOCK-ALLOCATE";drive #; track #;sector # usually abbreviated as: PRINT#15,"B-A";drive #; track #;sector # where "drive #" is the drive number, always 0 on the 1551, and "track #" and "sector
#" are the track and sector containing the block of data to be read into the file buffer.
60
ALTERNATE FORMAT:
PRINT#15,"B-A:";drive #; track #;sector #
EXAMPLE:
If 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 the next available track and block number. Therefore, before selecting a block to write, try 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 directory track. If the track number returned is 0, the diskette is full.
Here is a program that allocates a place to store a message on a diskette.
100 OPENI5,8, 15
110 OPEN5,8,5, "#"
120 PRINT#5,"1 THINK
THEREFORE I AM"
130T=I:S=1
140 PRINT#15,"B-A";0;T;S
150INPUT#15,EN,EM$,ET,ES
160 IF EN =0 THEN 210
170 IF EN<>65 THEN PRINT
EN ,EM$,ET ,ES:STOP
180 IF ET = 0 THEN PRINT
"DISK FULL":STOP
190 IF ET= 18 THEN ET= 19:ES=0
200T=ET:S=ES:GOTO 140
210 PRINT#15,"U2";5;0;T;S
220 PRINT "STORED AT:",T,S
230 CLOSE 5:CLOSE 15
240 END
Open command channel
" direct access "
Write a message to buffer
Start at first track & sector
Try allocating it
See if it worked
If so, we're almost done
"NO BLOCK" means already allocated
If next track is 0, we're out of room
Don't allocate the directory!
Try suggested track & sector next
Write buffer to allocated sector
Say where message went and tidy up
FREEING BLOCKS
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 OOS. Block-Free updates the BAM to show a particular sector is not in use, rather than actually erasing any data.
FORMAT FOR BLOCK-FREE COMMAND:
PRINT#15,"BLOCK-FREE";drive #;track #;sector # abbreviated as: PRINT#15,"B-F";drive #;track #;sector #
61
where "drive #" is the drive number (always 0 on the 1551), and "track #" and "sector
#" are respectively the track and sector numbers containing the desired hlock of data to be read into the file buffer.
ALTERNATE FORMAT:
PRINT#15,"B-F:";drive #;track #;sector #
EXAMPLE:
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:
PRINT# 15, "B-F" :0; 1:1
USING RANDOM FILES (ADVANCED USERS ONLY)
By combining the commands in this chapter, it is possible to develop a file-handling program that uses random files. What you need to know now is how to kecp track of which blocks on the disk such a file has used. (Even though you know a sector has not been allocated by your random file, you must also be sure it wasn't allocated by another unrelated file on the diskette.)
The most common way of recording which sectors have been used by a random file is in a sequential file. The sequential file stores a list of record numbers, with the track, sector, and byte location of each record. This means three channels are needed by a random file: one for the command channel, one for the random data, and the last for the sequential data.
62
CHAPTER 7
INTERNAL DISK COMMANDS
Expert programmers can give commands that directly alter the workings of the 1551 , much as skilled programmers can alter the workings of Basic inside the computer with
Peeks, Pokes and Sys calls, It is also possible to write machine language programs that load and run entirely within the 1551, either by writing them into disk memory from the computer, or by loading them directly from diskette into the desired disk memory buffer.
In use, this is similar to loading and running machine language programs in your computer.
As when learning to use PeekO, Poke and Sys in your computer, extreme caution is advised in using the commands in this chapter. They are essentially machine language commands, and lack all of Basic's safeguards. If anything goes wrong, you may have to tum the disk drive off and on again (after removing the diskette) to regain control. Do not practice these commands on any important diskette, Rather, make a spare copy and work with that. Knowing how to program a 6502 in machine language will help greatly, and you will also need a good memory map of the 1551. A brief 1551 map appears below.
1551 MEMORY MAP
Location
0000-0001
0002-00FF
OIOO-OIFF
0200-02FF
0300-06FF
0700-07FF
4000-4007
Cooo-FFE5
FFE6-FFFF
Purpose
8 bit port-651 OT
Zero page work area, * job queue, variables
GCR overflow area and stack
Command buffer, parser, tables, variables
4 data buffers, 0- 3
BAM resident in memory
6523a va to computer controller
16K byte ROM, DOS and controller routines
JMP table, user command vcctors
*
Job queue and HDRS offsct by 2 bytes-starts at $0002
Other Resources:
More detailed information about Commodorc disk drives can be found in these books:
Inside Commodorc DOS, by Immers & Ncufeld (Datamost, c1984)
The Anatomy of the 1541 Disk Drive, by Englisch & Szezepanowski
(Abacus, e1984)
Programming the PET/CBM, by West (Level Limitcd, cI982)
Thc PET Personal Computer Guide. by Osborne & Strasmas
(Osborne/McGraw-Hill. cI982)
63
MEMORY -READ
The disk contains 16K of ROM (Read-Only Memory), as well as 2K of RAM (Read-
Write Memory). You can get direct access to any location within these, or to the buffers that the DOS has set up in RAM, by using memory commands. Memory-Read allows you to select which byte or bytes to read from disk memory into the computer. The Memory-
Read command is the equivalent of the Basic PeekO function, but reads the disk's memory instead of the computer's 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 wording.
FORMAT FOR THE MEMORY-READ COMMAND:
PRINT # 15, "M -R "CHR$( <address )CHR$(> address )CHR$( # of bytes) where "<address" is the low order part, and ">address" is the high order part of the address in disk memory to be read. If the optional "# of bytes" is specified, it selects how many memory locations will be read in, from 1-255. Otherwise, I character will be read. If desired, a colon (:) may follow M-R inside the quotation marks.
ALTERNATE FORMAT:
PRINT#15, "M-R:"CHR$( <address)CHR$(>address)CHR$(# of bytes)
The next byte read using the Get# statement through channel #15 (the error channel), will be from that address in the disk controller's memory, and successive bytes will be from successive memory locations.
Any Input# from the error channel will give peculiar results when you're using this command. This can be cleared up by sending any other command to the disk, except another memory command.
EXAMPLES:
To see how many tries the disk will make to read a particular sector, and whether
"seeks" one-half track to each side will be attempted if a read fails, and whether
"bumps" to track one and back will be attempted before declaring the sector unreadable, we can use the following lines. They will read a special variable in the zero page of disk memory, called REVCNT. It is located at $6A hexadecimal ($6A hexadecimal = 6 x 16
+
10 = 106).
110 OPEN 15,8,15
120 PRINT#15, "M-R"CHR$(106)CHR$(0)
Open command channel
Same as G=PEEK(106)
64
130 GET# 15 ,G$:IF G$ = ", THEN G$ = CHR$(O)
140 G = ASC(G$)
150 B = G AND 128:B$ = "ON":lF B THEN B$ = "OFF" Check bit 7
160 S=G AND 64:S$= "ON":IF S THEN S$= "OFF' Check bit 6
170 T=G AND 31:PRINT "# OF TRIES IS";T
180 PRINT "BUMPS ARE";B$
190 PRINT "SEEKS ARE";S$
200 CLOSE 15
2\0 END
Check bits 0-5 and give results
Tidy up after
Here's a more general purpose program that reads one or more locations anywhere in disk memory:
110 OPENI5,8,15
120 INPUT"# OF BYTES TO READ (0 = END)";NL
130 IF NL< 1 THEN CLOSE 15:END
140 IF NL>255 THEN 120
150 INPUT"STARTING AT ADDRESS";AD
160 AH=INT(AD/256):AL=AD-AH*256
170 PRINT#15, "M-R"CHR$(AL)CHR$(AH)
CHR$(NL)
180 FOR 1= 1 TO NL
190: GET#15,A$:IF A$= "" THEN A$=CHR$(O)
200: PRINT ASC(A$);
210 NEXT I
220 PRINT
230 GOTO 120
Open command channel
Enter number of bytes wanted unless done or way out of line
Enter starting address
Convert it into disk form
Actual Memory-Read
Loop til have all the data printing it as we go
Forever
MEMORY-WRITE
The Memory-Write command is the equivalent of the Basic Poke command, but has its effect in disk memory instead of within the computer. M-W allows you to write up to
34 bytes at a time into disk memory. The Memory-Execute and some User commands can be used to run any programs written this way.
FORMAT FOR THE MEMORY-WRITE COMMAND:
PRINT# 15,' 'Mw'
'CHR$( <address)CHR$(>address)CHR$
(# of bytes)CHR$(data byte(s» where "<address" is the low order part, and ">address" is the high order part of the 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 1 or more byte values to be written into disk memory, each as a CHR$O value. If desired, a colon (:) may follow M-
W within the quotation marks.
65
ALTERNATE FORMAT:
PRINT# 15,' 'M-W:"CHR$( <address)CHR$(>address)CHR$
(# of bytes)CHR$(data byte(s))
EXAMPLES:
We can use this line to tum off the "bumps" when loading DOS-protected programs (i.e., programs that have been protected against being copied by creating and checking for specific disk errors).
PRINT# 15,' 'M- W' 'CHR$( 106)CHR$(0)CHR$( I)CHR$( 133)
The following line can be used to recover bad sectors, such as when an important file has been damaged and cannot be read normally.
PRINT# 15, "M-W"CHR$(l06)CHR$(0)CHR$( I )CHR$(3I)
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 inside the computer. As mentioned in the previous section's first example, location 106 in 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
I). Bit 6. if set, means no seeks. In that case, the dri ve won' t attempt to read the hal f-track above and below the assigned track to see if it can read the data that way. The bottom 6 bits are the count of how many times the disk will try to read each sector before and after trying seeks and bumps before giving up. Since 31 is the largest number that can be 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, and machine-language before using direct-access disk commands, as well as their potential power.
MEMORY -EXECUTE
Any routine in disk memory, either in RAM or ROM, can be executed with the
Memory-Execute command. It is the equivalent of the Basic Sys call to a machine language program or subroutine. but works in disk memory instead of within the computer.
FORMAT FOR THE MEMORY-EXECUTE COMMAND:
PRINT# 15,' 'M-E"CHR$( <address)CHR$(>address) where" <address" is the low order part, and" >address" is the high order part of the address in disk memory at which execution is to begin.
66
ALTERNATE FORMAT:
PRINT#15,' 'M-E:' 'CHR$( <address)CHR$(>address)
EXAMPLE:
Here is a Memory-Execute command that does absolutely nothing. The first instruction it executes is an RTS, which ends the command:
PRINT# 15, "M-E''CHR$( I 79)CHR$(242)
A more plausible use for this command would be to artificially trigger an error message.
Don't forget to check the error channel, or you'll miss the message:
PRINT# 15, "M-E' 'CHR$(201 )CHR$(239)
However, most uses require intimate knowledge of the inner workings of the DOS, and preliminary setup with other commands, such as Memory-Write.
BLOCK-EXECUTE
This rarely-used command will load a sector containing a machinc language routine into a memory buffer from diskette, and execute it from the first location within the buffer, until a ReTurn from Subroutine (RTS) instruction ends the command.
FORMAT FOR THE BLOCK-EXECUTE COMMAND:
PRINT#15,"B-E";channel #;drive #:track #;sector # where "channel #" is the channel number specified when the file into which the block will be loaded was opened, "drive #" is the drive number (always 0 on the 1541), and
"track #" and "sector #" arc respectively the track and sector numbers containing the desired block of data to be loaded into the file buffer and executed there.
ALTERNATE FORMATS:
PRINT# 15 ,"B-E:";channel #;drive #;track #;sector #
PRlNT# 15, "B-E:channel # ,drive # ,track # ,sector #"
EXAMPLES:
Assuming you've written a machine language program onto Track I, Sector 8 of a diskette, and would like to run it in buffer number I ip disk memory (starting at $0400 hexadecimal, you could do so as follows: llOOPEN 15,8,15
120 OPEN 2,8,2,"#1"
Open command channel
Open direct access channel to buffer 1
67
130 PRINT#15,"B-E";2;0;1;8
140 CLOSE 2
150 CLOSE 15
160 END
Load Track I, Sector 8 in it
Tidy up after
& execute
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 ofthem 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 1551 without changing its variables, UJ cold-starts the 1551 almost as if it had been turned off and on again.
User Command ul or ua u2 or ub u3 or uc u4 or ud uS or ue u6 or uf u7 or ug u8 or uh. u9 or ui u: or uj
Function block read replacement block write replacement jump to $0500 jump to $0503 jump to $0506 jump to $0509 jump to $050c jump to $050f jump to ($fffa) reset tables power up vector
By loading these memory locations with another machine language JMP command, such as JMP $0520, you can create longer routines that operate in the disk's memory along with an easy-to-use jump table.
FORMAT FOR USER COMMANDS:
PRINT#15, "Ucharacter" where "character" defines one of the preset user commands listed above.
EXAMPLES:
PRINT# 15, "U:"
PRINT# 15, "U3"
Preferred form of DOS RESET command
Execute program at start of buffer 2
68
UTILITY LOADER
This command loads a user-type file into the drive RAM. The first two bytes of the file must contain the low and high addresses respectively. The third byte is the amount of characters to follow. In addition, a trailing checksum byte must be included. The load address is the starting address.
FORMAT FOR THE UTILITY LOADER COMMAND
PRINT #' , &0: filename' ,
69
CHAPTER 8
MACHINE LANGUAGE PROGRAMS
Here is a list of disk-related Kernal ROM subroutines and a practical example of their use in a program which reads a sequential tile into memory from disk. Note that most require advance setup of one or more processor registers or memory locations, and all arc called with the assembly language JSR command.
For a more complete description as to what each routine docs and how parameters are set for each routine, see the Programmer's Reference Guide for your specific computer.
Label
SETLFS
SETNAM
OPEN
CLOSE
CHKIN
CHKOUT
CLRCHN
CHRIN
CHROUT
START
NEXT
DISK-RELATED KERNAL SUBROUTINES
Address
$FFBA
$FFBD
$FFCO
$FFC3
$FFC6
$FFC9
$FFCC
$FFCF
$FFD2
Function
;SET LOGICAL, FIRST & SECOND ADDRESSES
;SET LENGTH & ADDRESS OF FILENAME
:OPEN LOGICAL FILE
;CLOSE LOGICAL FILE
;SELECT CHANNEL FOR INPUT
;SELECT CHANNEL FOR OUTPUT
;CLEAR ALL CHANNELS & RESTORE
DEFAULT 110
;GET BYTE FROM CURRENT INPUT DEVICE
;OUTPlJT BYTE TO CURRENT OUTPUT
DEVICE
LOA
LOX
LOY
JSR
LOA
LOX
LOY
JSR
JSR
LOX
JSR
JSR
BEQ
JSR
1MP
#4 ;SET LENGTH & ADDRESS
#<FNADR ;OF FILE NAME, LOW
#>FNADR :& HIGH BYTES
SETNAM ;FOR NAME SETTER
#3
#8
;SET FILE NUMBER,
;DISK DEVICE NUMBER,
#0
SETLFS
OPEN
;AND SECONDARY ADDRESS
;AND SET THEM
;OPEN 3,8,0, "TEST"
#3
CHKIN ;SELECT FILE 3 FOR INPUT
CHRIN
END
;GET NEXT BYTE FROM FILE
;UNTIL FINISH OR FAIL
CHROUT ;OUTPUT BYTE TO SCREEN
NEXT ;AND LOOP BACK FOR MORE
END
FNADR
LDA
JSR
JSR
RTS
#3 ;WHEN DONE
CLOSE ;CLOSE FILE
CLRCHN ;RESTORE DEFAULT 110
;BACK TO BASIC
.BYT "TEST" ;STORE FILE NAME HERE
70
APPENDIX A: CHANGING THE DEVICE NUMBER
SOFTWARE METHOD
The preferred way to temporarily change the device number of a disk drive is via a program. When power is first turned on. the drive reads an 110 location whose value is controlled by ajumper on its circuit board, and writes the device number it reads there into memory locations 119 and 120. Any time thereaftcr, you may write over that device number with a new one, which will be effective until it is changed again, or the 1551 is reset.
FORMAT FOR TEMPORARILY CHANGING THE DISK DEVICE NUMBER:
PRINT# IS. "%n"
Wherc n 8 or 9
EXAMPLE:
Here is a program that sets any device number:
10 INPUT "NEW DEVICE NUMBER"; DV$
20 IF NOT (DV$ = "8" or DV$ = "9") THEN 10
30 OPEN 15,8,15, "%R"
+
DV$: CLOSE 15
If you send only the % sign, the device number will toggle bctwccn 8 and 9.
Note: If you will bc using two disk drives, and want to temporarily change the device number of onc, you will need to run the abovc program with the disk drive whose device number is not to be changed turned off. After the program has been run, you may turn that drive back on. If you need to connect more than two drives at once, you will need to use the hardware method of changing device numbers.
HARDWARE METHOD
IMPORTANT: Using the following method to change the device number will void the 1551 Disk Dri ve warranty!
71
If you have more than one drive, either you or preferably your dealer may permanently change the address of all after the first, to avoid having to run the program on the previous page before each use of multiple drives. The only tools needed to make the change are a Phillips-head screwdriver and a sharp knife.
STEPS TO CHANGE THE DEVICE NUMBER ON HARDWARE
1. Disconnect all cables from drive, including power.
2. Turn drive upside down on a flat, steady surface.
3. Remove 4 screws on bottom that hold drive cover together.
4. Carefully turn drive right side up, and remove case top.
5. Remove 2 screws on side of metal housing covering the main circuit board.
6. Remove housing.
7. Locate the device number jumper. It will be a small round silvery spot (solder pads) on the main circuit board.
8. Make the cut by completing the cut already nearly separating the two halves of the jumper.
9. Replace the metal housing and its 2 screws.
10. Replace case top, carefully turn drive upside down, and tighten 4 case screws.
11. Re-connect cables and power up.
Note: If your needs change later, a cut jumper can be restored with a small dot of electrical solder. However, do not attempt this yourself unless you are already skilled at electronic soldering.
72
APPENDIX B: DOS ERROR MESSAGES AND LIKELY CAUSES
Note: Many commercial program diskettes are intentionally created with one or 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 program diskette, check the program's manual. If its copyright statement does not permit purchasers to copy the program for their own use, you may not be able to duplicate the diskette. In some such cases, a safety spare copy of the program diskette is available from your dealer or directly from the company for a reasonable fee.
00: OK (not an error)
This is the message that usually appears when the error channel is checked. It means there is no current error in the disk unit.
OJ: FILES SCRATCHED (not an error)
This is the message that 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.
20: READ ERROR (block header not found)
The disk controller is unable to locate the header of the requested data block.
Caused by an illegal block, or a header that has been destroyed. Usually unrecoverable.
21: READ ERROR (no sync character)
The disk controller is unable to detect a sync mark on the desired track. Caused by misalignment, or a diskette that is absent. unformatted or improperly seated. Can also indicate hardware failure. Unless caused by one of the above simple causes, this error is usually unrecoverable.
22: READ ERROR (data block not present)
The disk controller has been requested to read or verify a data block that was not properly written. Occurs in conjunction with Block commands and indicates an illegal track and/or sector request.
23: READ ERROR (checksum error in data block)
There is an error in the data. The sector has been read into disk memory, but its checksum is wrong. May indicate grounding problems. This fairly minor error is often repairable by simply reading and rewriting the sector with direct access commands.
73
24: READ ERROR (byte decoding error)
The data or header has been read into disk memory. but a hardware error has been created by an invalid bit pattern in the data byte. May indicate grounding problems.
25: WRITE ERROR (write-verify error)
The controller has detected a mismatch between the data written to diskette and the same data in disk memory. May mean the diskette is faulty. If so, try another. Usc only high quality diskettes from reputable makers.
26: WRITE PROTECT ON
The controller has been requested to write a data block while the write protect sensor is covered. Usually caused by writing to a diskette whose write protect notch is covered over with tape to prevent changing the diskette's contents.
27: READ ERROR (checksum error in header)
The controller detected an error in the header byte, of the requested data block. The block was not read into disk memory. May indicate grounding problems. Usually unrecoverable .
28: WRITE ERROR (long data block)
The controller attempts to detect thc sync mark of the next header after writing a data block. If the sync mark does not appear on time. this error message is generated. It is caused by a bad diskette format (the data extends into the next block) or by a hardware failure.
29: DISK ID MISMATCH
The disk controller has been requested to access a di,kette which has not been initialized. Can also occur if a diskette has a bad header.
30: SYNTAX ERROR (general syntax)
The DOS cannot interpret the command sent to the command channel. Typically. this is caused by an illegal number of file names, or an illegal pattern. Check your typing and try again.
31: SYNTAX ERROR (invalid command)
The DOS does not recognize the command. It must begin with the first character sent. Check your typing and try again.
32: SYNTAX ERROR (invalid command)
The command sent is longer than 58 characters. Use abbreviated di,k commands.
33: SYNTAX ERROR (invalid file name)
Pattern matching characters cannot be used in the Save command or when Opening files for the purpose of Writing new data. Spell out the tile name.
74
34: SYNTAX ERROR (no file given)
The file name was left out of a command or the DOS does not recognize it as such.
Typically. a colon (:) has been omitted. Try again.
39: SYNTAX ERROR (invalid command)
The DOS does not recognize a command sent to the command channel (secondary address 15). Check your typing and try again.
50: RECORD NOT PRESENT
The requested record number has not been created yet. This is not an error in a new relative file or one that is being intentionally expanded. It results from reading past the last existing rccord. or positioning to a non-existent record number with the
Record# command.
51: OVERFLOW IN RECORD
The data to be written in the current record exceeds the record size. The excess has been truncated (cut off). Be sure to include all special characters (such as carriage returns) in calculating record sizes.
52: FILE TOO LARGE
There isn't room left on the diskette to create the requested relative record. To avoid this error, create the last record number that will be needed as you first create the file. If the file is unavoidably too large for the diskette, either split it into two files on two diskettes, or use abbreviations in the data to allow shorter records.
60: WRITE FILE OPEN
A write file that has not been closed is being re-opened for reading. This file must be immediately rescued. as described in Housekeeping Hint #2 in Chapter 4. or it will become a splat (improperly closed) tile and probably be lost.
61: FILE NOT OPEN
A file is being accessed that has not been opened by the DOS. In some such cases no error message is generated. Rather the request is simply ignored.
62: FILE NOT FOUND
The requested file does not exist on the indicated drive. Check your spelling and try again.
63: FILE EXISTS
A file with the same name as has been requested for a new file already exists on the diskette. Duplicate file names are not allowed. Select another name.
64: FILE TYPE MISMATCH
The requested file access is not possible using files of the type named. Reread the chapter covering that file type.
75
65: NOBLOCK
Occurs in conjunction with B-A. The sector you tried to allocate is already allocated. The track and sector numbers returned are the next higher track and sector available. If the track number returned is zero (0), all remaining sectors are full. If the diskette is not full yet, try a lower track and sector.
66: ILLEGAL TRACK AND SECTOR
The DOS has attempted to access a track or sector which does not exist. May indicate a faulty link pointer in a data block.
67: ILLEGAL SYSTEM TOR S
This special error message indicates an illegal system track or block.
70: NO CHANNEL (available)
The requested channel is not available, or all channels are in use. A maximum of three sequential files or one relative file plus one sequential file may be opened at one time, plus the command channel. Do not omit the drive number in a sequential
Open command, or only two sequential files can be used. Close all files as soon as you no longer need them.
71: DIRECTORY ERROR
The BAM (Block Availability Map) on the diskette does not match the copy in disk memory. To correct. Initialize the diskette.
72: DISK FULL
Either the diskette or its directory is full. DISK FULL is sent when 2 blocks are still available, allowing the current file to be closed. If you get this message and the directory shows any blocks left, you have too many separate files in your directory, and will need to combine some, delete any that are no longer needed, or copy some to another diskette.
73: DOS MISMATCH (CBM DOS V2.6 TDISK" .0)
If the disk error status is checked when the drive is first turned on, before a directory or other command has been given, this message will appear. In that use, it is not an error, but rather an easy way to see which version of DOS is in use. If the message appears at other times, an attempt has been made to write to a diskette with an incompatible format, such as the former DOS I on the Commodore 2040 disk drive. Use one of the copy programs on the Test/Demo diskette to copy the desired file(s) to a 1551 diskette.
74: DRIVE NOT READY
An attempt has been made to access the 1551 single disk without a formatted diskette in place. Blank diskettes cannot be used until they have been formatted.
76
APPENDIX C: DISKETTE FORMATS
Expanded View of a Single Sector
/
/
/
/
/
/
/
NOTE
Not to scale
77
SYNC 1
08
CHECKSUM
SECTOR
TRACK lOl, lO2
GAPI
SYNC 2
07
BYTEO, BYTEI
DATA
CHECKSUM 2
GAP 2
40 bits of ones (all l's is the highest write frequency).
Disk I.D. field identification mark.
Checksum of lO 1, lO2, SECTOR, TRACK.
The number of this sector
Track which this sector resides on.
2 bytes (20 bits) indicating the diskette I.D. (the I.D. is specified by the user when the diskette is formatted).
72 bits of GCRO or 010 10 10 1 (8 bit byte x 9)
40 bits of ones.
Disk data field identification mark.
Track and sector of next related block.
254 bytes (2540 bits) of data.
Checksum of BYTEO, BYTEI,andDATA.
Variable gap of GCR O. This gap is variable depending on the speed of the disk during format. GAP 2 will be constant for all sectors except for the tail gap (the gap between I st and the last sectors).
1551 Format: Expanded View of a Single Sector
1551 BLOCK DISTRIBUTION BY TRACK
Track number
I to 17
18 to 24
25 to 30
31 to 35
Range of Sectors o to 20 o to 18 o to 17 o to 16
Total # of Sectors
21
19
18
17
1551 BAM FORMAT
Track 18, Sector O.
BYTE CONTENTS DEFINITION
0,1
2
3
4-143
18,01
65
0
Track and sector of first directory block.
ASCII character A indicating 1551/4040 format.
Null flag for future DOS use.
Bit map of the available blocks in tracks 1-35.
% 1
=
available block
%0
=
block not available (each bit represents one block)
78
BYTE
144-159
160-161
162-163
164
165-166
167-170
170-255
1551 DIRECTORY HEADER
Track 18, Sector O.
CONTENTS
160
160
50,65
160
0
DEFINITION
Diskette name padded with shifted spaces.
Shifted spaces.
Diskette ID.
Shifted space
ASCII representation of 2A, which are, respectively, the DOS version (2) and format type (1551/4040).
Shifted spaces.
Nulls ($00), not used.
PROGRAM FILE FORMAT
BYTE
FIRST SECTOR
DEFINITION
0,1
2,3
4-255
Track and sector of next block in program file. I
Load address of the program
Next 252 bytes of program information stored as in computer memory (with key words tokenized).
REMAINING FULL SECTORS
0,1
2-255
Track and sector of next block in program file. I
Next 254 bytes of program info stored as in computer memory
(with key words tokenized).
FINAL SECTOR
0,1
2-???
Null ($00), followed by number of valid data bytes in sector.
Last bytes of the program information, stored as in computer memory (with key words tokenized). The end of a Basic file is marked by 3 zero bytes in a row. Any remaining bytes in the sector are garbage, and may be ignored.
79
SEQUENTIAL FILE FORMAT
BYTE
ALL BUT FINAL SECTOR
DEFINITION
0-1
2-255
Track and sector of next sequential data block.
254 bytes of data.
FINAL SECTOR
0,1
2-???
Null ($00), followed by number of valid data bytes in sector.
Last bytes of data. Any remaining bytes are garbage and may be ignored.
1551 RELATIVE FILE FORMAT
BYTE
DATA BLOCK
DEFINITION
0,1
2-255
Track and sector of next data block.
254 bytes of data. Empty records contain $FF
(all binary ones) in the first byte followed by $00
(binary all zeros) to the end of the record. Partially filled records are padded with nulls ($00).
SIDE SECTOR BLOCK
0-1
2
3
4-5
6-7
8-9
10-11
12-13
14-15
16-255
Track and sector of next side sector block.
Side sector number (0-5)
Record length
Track and sector of first side sector (number 0)
Track and sector of second side sector (number 1)
Track and sector of third side sector (number 2)
Track and sector of fourth side sector (number 3)
Track and sector of fifth side sector (number 4)
Traek and sector of sixth side sector (number 5)
Track and seetor pointers to 120 data blocks.
80
1551
DIRECTORY FILE FORMAT
Track 18, Sector 1.
BYTE
0, I
2-31
34-63
66-95
98-127
130-159
162-19\
194-223
226-255
DEFINITION
Track and sector of next directory block.
File entry 1*
File entry 2*
File entry 3
*
File entry 4*
File entry 5 *
Fi Ie entry 6
*
File entry 7*
File entry 8*
*STRUCTURE OF EACH INDIVIDUAL DIRECTORY ENTRY
BYTE CONTENTS DEFINITION
0
1-2
3-18
19-20
21
22-25
26-27
28-29
128
+ type
File type OR 'ed with $80 to indicate properly closed file.
(if OR' ed with $CO instead, file is locked.)
TYPES: 0 DELeted
I
2
= SEQuential
= PROGram
3
4
= USER
= RELative
Track and sector of first data block.
File name padded with shifted spaces.
Relative file only: track and sector of first side sector block.
Relative file only: Record length.
Unused.
Track and sector of replacement file during an
@SAVE or @OPEN.
Number of blocks in file: stored as a two-byte integer, in low byte, high byte order.
81
APPENDIX D: DISK COMMAND QUICK REFERENCE CHART
General Format: OPEN 15,8, 15:PRINT# 15,command:CLOSE 15 (Basic 2)
HOUSEKEEPING COMMANDS
NEW
COpy
RENAME
SCRATCH
VALIDATE
INITIALIZE
HEADER "diskette name,Iid" ,DO
COPY "old tile" TO "new tile"
RENAME "old name" TO "new name"
SCRATCH "tile name"
COLLECT
"10"
FILE COMMANDS
LOAD
SAVE
CLOSE
GET#
INPUT#
OPEN
PRINT#
RECORD#
DLOAD "tile name"
DSA VE "tile name"
CLOSE file #
GET#tile #, variable list
INPUT#llle #,variable list
OPEN file # ,device # ,channel #, "command string"
PRINT#file #,data list
"P"CHR$(channel #)CHR$«record #)
CHR$( >record # )CHR$( offset)
DIRECT ACCESS COMMANDS
BLOCK-ALLOCATE
BLOCK-EXECUTE
BLOCK-FREE
BUFFER-POINTER
BLOCK-READ
BLOCK-WRITE
MEMORY-EXECUTE
MEMORY-READ
MEMORY-WRITE
"B-A";O;track #;seetor #
"B-E";channel #;O;track #;sector #
"B-F" ;O;track #;sector #
"B-P" ;channel #;byte
"UI ";channel #;O;track #;seetor #
"U2";channel #;O;track #;sector #
"M-E' 'CHR$( <address)CHR$( >address)
"M-R"CHR$( <address)CHR$(>address)CHR$( # of bytes)
"M-W"CHR$( <address)CHR$(>address)CHR$( # of bytes)
CHR(data byte)
USER
CHANGE RETRY
"Ucharacter"
"'70R" + CHR$ (retry) min = 1 max = 255
CHANGE SECTOR
INTERLEAVE
UTILITY LOADER
"'70S"
+
CHR$ (interleave) default = 17
"&O:filename' ,
82
APPENDIX E: TEST IDEMO DISKETTE
HOW TO USE
The "HOW TO USE" programs provide brief descriptions of the other programs on the
TestlDemo
diskette.
THE VIC·20 & C-64 WEDGES
Additional commands are available which allow you to type short instructions to the disk drive. Load and run the VIC-20 WEDGE if you have a VIC; use the C-64
WEDGE if you have a Commodore 64. Using either, you will be able to press backslash
(I) followed by the program name and the RETURN key to load a program; the "I" means load from disk drive. For example, type" Ihow to use" to load that program.
Type" >" or "@" and then press RETURN to display the current disk error status.
Type" > $" or "@$" and RETURN to display the directory without erasing the current program.
DOSS.1
The DOS 5.1 program is not intended to be loaded directly, but is loaded instead from the program C-64 WEDGE. Its load address is $CC00 hexadecimal.
PRINTER TEST
The PRINTER TEST prints a listing of characters in a form that makes it easy to check the mechanical and electronic capabilities of the printer.
DISK ADDR CHANGE
Use this program to change the device number of the disk drive. It is a soft change-when the system is turned off, the disk drive is reset to its original device number.
VIEW BAM
The VIEW BAM program allows a programmer to examine the contents of the sectors that make up the block availability map (BAM)-the table that DOS uses to identify blocks that have been allocated to the files on that diskette.
CHECK DISK
The CHECK DISK program can be used to make sure a new diskette that has been headered is in fact a good diskette. The program writes to every block to verify its ability to store information and identifies any diskette that contains a bad block. Don't use such diskettes.
83
DlSPLAYT&S
The DISPLAY T&S program allows a programmer to examine the contents of a block by specifying the particular track number and sector number that identifies that block.
PERFORMANCE TEST
The PERFORMANCE TEST program tests the electronic and mechanical capabilities of the disk drive whenever necessary. Use this program whenever you suspect there may bl;: damage to the drive.
SEQ.FILE.DEMO AND REL.FILE.DEMO
These two files are included as programming examples or guidelines when writing your own programs. They also illustrate the important technique of checking the error channel after each access to the disk drive.
SD.BACKUP.xx
These three programs are entitled SD.BACKUP.C64, SD.BACKUP.CI6, and
SD.BACKUP.PLUS4. Each, when loaded 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.UTlL, PRINT.+4, and
PRINT.CI6.UTlL. 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 program 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.
CM BASIC DEMO +4 BASIC DEMO
These programs offer a set of demo routines which can perform minimal system testing on the computers. Routines are provided for testing the video and sound output, keyboard and joy stick input, and disk unit I/O.
LOAD ADDRESS
LOAD ADDRESS is a simple program that tells you where a program was originally located in memory. Some programs can only run in the same locations from which they were saved. Load such programs with LOAD"filename" ,8, I.
84
UN SCRATCH
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.
ALL ADDITIONS, DELETIONS, OR MODIFICATIONS TO THE PRO-
GRAMS LISTED IN THIS APPENDIX WILL BE NOTED IN THE "HOW TO
USE" PROGRAMS ON YOUR TEST IDEMO DISKETTE.
85
APPENDIX F: SPECIFICATIONS OF THE 1551 DISK DRIVE
STORAGE
Total formatted capacity
Maximum Sequential file size
Maximum Relative fiJe size
Records per file
Files per diskette
Tracks per diskette
Sectors per track
Sectors per diskette
Bytes per sector
174848 bytes per diskette
168656 bytes per diskette
167132 bytes per diskette
65535
144
35
17-21
683 total
664 free for data
256
INTEGRA TED CIRCUIT CHIPS USED
6510T microprocessor. 110
6523A 1/0
23128
4016
16K bytes ROM
2K bytes RAM
Gate Array Controller circuit
PHYSICAL DIMENSIONS
Height
Width
Depth
Weight
97 mm
200mm
374mm
10.5 kg
ELECTRICAL REQUIREMENTS
Three wire-grounded detachable power cable.
Voltage U.S.
Export
100-120 VAC
220-240 VAC
Frequency U.S. 60 HZ
Power used
Export 50HZ
25 Watts
MEDIA
Any good quality SIf4 inch diskette may be used (Commodore diskettes are recommended).
86
Letöltés
Hirdetés