How to determine if a file exists or not?

Basic and Machine Language

Moderator: Moderators

Post Reply
Bobbi
Vic 20 Afficionado
Posts: 355
Joined: Thu Oct 13, 2016 11:35 am
Location: Toronto
Occupation: Programmer

How to determine if a file exists or not?

Post by Bobbi »

I am wondering what is the correct way to determine if a file on disk exists or not under the VIC-20 kernal / Commodore DOS.

If I do the following in BASIC:

Code: Select all

10 OPEN2,8,2,"DOESNTEXIST,S,R"
20 GET#2,A$
30 PRINTASC(A$)
40 CLOSE2
It prints 199. Is that some magic value meaning end-of-file? The 1541 User's Manual does not provide much assistance here. Is there a better programmer's reference for disk stuff?
Bobbi
Vic 20 Afficionado
Posts: 355
Joined: Thu Oct 13, 2016 11:35 am
Location: Toronto
Occupation: Programmer

Re: How to determine if a file exists or not?

Post by Bobbi »

I think I answered my own question. I should look at the value of ST. The '64' bit is end-of-file.

Code: Select all

10 OPEN2,8,2,"DOESNTEXIST,S,R"
20 GET#2,A$
30 IF (ST AND 64) <> 0 THEN GOSUB 1000
40 CLOSE 2
50 END
1000 PRINT "DOESN'T EXIST"
1010 RETURN
Bobbi
Vic 20 Afficionado
Posts: 355
Joined: Thu Oct 13, 2016 11:35 am
Location: Toronto
Occupation: Programmer

Re: How to determine if a file exists or not?

Post by Bobbi »

However this doesn't distinguish between zero-length file and a file that truly does not exist. How to do that?
User avatar
Mike
Herr VC
Posts: 4816
Joined: Wed Dec 01, 2004 1:57 pm
Location: Munich, Germany
Occupation: electrical engineer

Re: How to determine if a file exists or not?

Post by Mike »

CBM DOS can't have zero-length files. *) ;)

However, you can (try to) rename a file into itself and check the error channel, like thus:

Code: Select all

10 DN=PEEK(186):INPUT"FILE";N$
15 OPEN15,DN,15,"R0:"+N$+"="+N$:DS$=""
20 GET#15,A$:DS$=DS$+A$:IFST=0THEN20
25 CLOSE15:PRINTDS$
Unless there are other issues (like write protect on, or drive not ready, etc.), you either get 62,FILE NOT FOUND,00,00 or 63,FILE EXISTS,00,00 in DS$ ... which exactly match the information you want to know. :)

And this method also has the charm it works independent of CBM DOS file type.

Cheers,

Michael


*) actually your example would instead fail with files of one byte length, as EOF in ST already is signalled with the last byte sent!

Edit: actually, CBM DOS doesn't correctly handle one-byte-length files, either - in both cases (zero-length, one byte) a read back results in a file having four bytes length. This happens on the 1541 and 1581 (and presumably, also the 1571).
Bobbi
Vic 20 Afficionado
Posts: 355
Joined: Thu Oct 13, 2016 11:35 am
Location: Toronto
Occupation: Programmer

Re: How to determine if a file exists or not?

Post by Bobbi »

Thanks Mike. Glad I asked - not sure I would have come up with that solution on my own!!
Post Reply