BBC BASIC for Windows
Programming >> Database and Files >> Error Handling When Deleting File
http://bb4w.conforums.com/index.cgi?board=database&action=display&num=1374912560

Error Handling When Deleting File
Post by Matt on Jul 27th, 2013, 08:09am

Hi,

Having trouble working out how to trap and use an 'Access denied' error during a delete file routine.

Code:
      DEF FN_delfile(file$)
      LOCAL dir%, sh%
      ON ERROR LOCAL IF ERR = 189 THEN = FALSE
      DIM dir% LOCAL 317
      SYS "FindFirstFile", file$, dir% TO sh%
      IF sh% <> -1 THEN SYS "FindClose", sh% ELSE = FALSE
      OSCLI "DELETE """ + file$ + """"
      = TRUE 


This still errors on the OSCLI line without producing an error report. What am I doing wrong? I've checked the help and it doesn't seem to allow error handling within the subroutine itself - or am I, as usual, missing something?

Matt
Re: Error Handling When Deleting File
Post by admin on Jul 27th, 2013, 09:28am

on Jul 27th, 2013, 08:09am, Matt wrote:
Having trouble working out how to trap and use an 'Access denied' error during a delete file routine.

I can't reproduce that. What is causing the 'Access denied' error? I've tried using your FN_delfile() routine with a file that doesn't exist, and a file set to read-only, and in both cases it returns zero without any error being reported.

Incidentally there's an easier way of testing whether a file exists than using FindFirstFile, just attempt to open it using OPENIN:

Code:
      F% = OPENIN(file$)
      IF F% CLOSE #F% : PRINT "File exists" 

I should also point out that in fact there's no point first testing whether the file exists, because there's a finite chance that it did exist when FindFirstFile is called, but by the time the OSCLI statement is executed it no longer exists (because an intervening task switch ran a process that deleted the file).

So because of that, admittedly small, chance you might just as well not bother to test whether the file exists and let the delete fail:

Code:
      DEF FN_delfile(file$)
      ON ERROR LOCAL = FALSE
      OSCLI "DELETE """ + file$ + """"
      = TRUE 

One final suggestion is that you can avoid an error occurring altogether by calling the DeleteFile API:

Code:
      DEF FN_delfile(file$)
      LOCAL R%
      SYS "DeleteFile", file$ TO R%
      = (R% <> 0) 

Richard.