r/apple2 • u/AutomaticDoor75 • 6d ago
Does that text file already exist?
I was trying to think of a way to check if a file with the same name already exists before saving a new one.
If this is already a well-known way of dealing with this, I'm sorry. I wanted to share this for anyone else who is getting started with BASIC on the Apple II.
This comes from page 59 of Apple II: The DOS Manual
Here's a quick way to delete any file named SCORES and re-OPEN it for new data, whether or not that file already exists:
5 REM SCORES DELETER
10 D$ = "" : REM D$ IS CTRL-D
15 PRINT D$;"OPEN SCORES"
20 PRINT D$;"DELETE SCORES"
25 PRINT D$;"OPEN SCORES"
30 REM REMAINDER OF PROGRAM HERE
3
u/Sick-Little-Monky 4d ago
Line 10 brings back memories. It's much clearer to use D$ = CHR$(4).
(Hopefully I got that right. It's been a while.) Here's the memory it triggered. In '83 I turned 13 and our family didn't have an Apple II yet, so I would use any means possible to get in front of one. My dad took me along to visit one of his friends.
This guy had typed in a whole file management program in Applesoft Basic from a magazine, starting with that exact Ctrl-D statement, REM and all. He was very chuffed about it, even though it didn't work. So I edited the line and typed the Ctrl-D in there, which he hadn't understood, and then he was amazed - and really happy.
2
u/AutomaticDoor75 4d ago
Thanks for sharing that memory!
I would write out CHR$(4) for a program. I wanted to copy the example program exactly as it was presented in the book.
1
u/Sick-Little-Monky 4d ago
Fair enough. I just wanted to reminisce, and remind people it's a design anti-pattern, as we would say now.
6
u/thefadden 5d ago edited 4d ago
You can use the VERIFY command to see if a file exists, but that can be a little slow for larger files. The UNLOCK command is faster, but if the user locked the file on purpose this could make things weird. (You would also need to test the error code to get correct behavior on write-protected disks.)
ONERR GOTO error code info is on page 114 of the manual you linked. See the Applesoft Manual for details on the mechanism.
FWIW, in ProDOS the VERIFY command just tests for the existence of the file, rather than scanning the entire thing.
6
u/DennisGK 6d ago edited 5d ago
I believe that program will crash with an error message in line 15 if the file SCORES exists in the disk but isn’t a text file. And it will definitely crash in line 20 if the file is locked. A more elegant solution is ONERR GOTO. Any error, either in BASIC such as typing a word when it wants to input a number or in DOS will send it to the line specified after GOTO. PEEK (222) will provide a code telling you what the error was. An error-handling routine can then determine how to proceed.
(Edited to fix my stupid typo.)