Page 1 of 1
How to check if a file exist? Newbie
Posted: Sat Apr 25, 2015 11:11 am
by rkn704
I want to delete a file if it already exists. There will be occasions when it does not exist. Is there a neat way of doing this.
I propose to use the KILL command to delete the file(s) and if a 'File not Found' error is returned use the ON ERROR RESUME NEXT to move on to the next command/function.
Thanks in advance.
Re: How to check if a file exist? Newbie
Posted: Tue Apr 28, 2015 10:45 am
by burger2227
No ERROR necessary:
Code: Select all
FUNCTION Exist% (filename$)
f% = FREEFILE
OPEN filename$ FOR APPEND AS #f%
IF LOF(f%) THEN Exist% = -1 ELSE Exist% = 0: CLOSE #f%: KILL filename$ 'delete empty files
CLOSE #f%
END FUNCTION
Usage in a program:
Code: Select all
INPUT "Enter a file name: ", file$
IF Exist%(file$) THEN OPEN file$ FOR INPUT AS #1: found% = -1 'function call demo
CLOSE #1
IF found% THEN PRINT "File exists!" ELSE PRINT "File not found!"
END
QB64 has the _FILEEXISTS function that does the same thing.
Re: How to check if a file exist? Newbie
Posted: Wed Apr 29, 2015 8:23 am
by rkn704
Thanks for the reply. Looks like it is time to lean about Functions, I will give it a go.
Re: How to check if a file exist? Newbie
Posted: Wed Apr 29, 2015 8:42 am
by burger2227
SUB and FUNCTION procedures are placed after the end of code in a program.
Code: Select all
INPUT "Enter a file name: ", file$
IF Exist%(file$) THEN OPEN file$ FOR INPUT AS #1: found% = -1 'function call demo
CLOSE #1
IF found% THEN PRINT "File exists!" ELSE PRINT "File not found!"
END
FUNCTION Exist% (filename$)
f% = FREEFILE
OPEN filename$ FOR APPEND AS #f%
IF LOF(f%) THEN Exist% = -1 ELSE Exist% = 0: CLOSE #f%: KILL filename$ 'delete empty files
CLOSE #f%
END FUNCTION
Qbasic will compile it and DECLARE them for you. QB64 does not require any DECLARE statements.
http://www.qb64.net/wiki/index.php/FILEEXISTS
Re: How to check if a file exist? Newbie
Posted: Mon May 04, 2015 11:14 am
by rkn704
Thanks for the assistance. I did have to add another CLOSE #F%
Code: Select all
FUNCTION EXIST% (FILENAME$)
F% = FREEFILE
OPEN FILENAME$ FOR APPEND AS #F%
IF LOF(F%) THEN
EXIST% = -1
CLOSE #F% ' without this I got 'File already Open' if the file did exist.
ELSE
EXIST% = 0
CLOSE #F%
KILL FILENAME$
CLOSE #F%
END IF
END FUNCTION