Page 1 of 1

Control if file is used before deletefile()

Posted: Mon May 27, 2019 4:44 pm
by sinisrus
Hello, (sorry for my bad english)

how do I know if a file is in use before erasing it?

Thank you

Re: Control if file is used before deletefile()

Posted: Mon May 27, 2019 5:01 pm
by airsoftsoftwair
That's not possible and doesn't make sense in a multitasking environment. Even if there was a function called IsFileInUse() it wouldn't make sense because some other process could lock the file between your call to IsFileInUse() and the call to DeleteFile()...

Re: Control if file is used before deletefile()

Posted: Mon May 27, 2019 11:39 pm
by sinisrus
For example I open picture with multiview or picshow and with my program hollywood I want to erase this picture my program will return an error and quit ... it's not very clean

Re: Control if file is used before deletefile()

Posted: Tue May 28, 2019 10:09 am
by jPV
You can disable the internal error handler before trying to delete a file, check yourself if it failed, and enable the error handler again after that.

If you're using it often, maybe it's better to write an own delete function, like this:

Code: Select all

Function p_DeleteFile(file$)
    Local code
    ExitOnError(False)
    DeleteFile(file$)
    code = GetLastError()
    ExitOnError(True)
    If code
        DebugPrint("Error while deleting \"" .. file$ .. "\":", GetErrorName(code))
    Else
        DebugPrint("\"" .. file$ .. "\" deleted.")
    EndIf
    Return(code)
EndFunction

StringToFile("bla", "testfile")          ; Create a new file
OpenFile(1, "testfile", #MODE_READWRITE) ; Let's keep the file open
p_DeleteFile("testfile")                 ; Deleting fails, but the script continues
CloseFile(1)                             ; Let's close the file
p_DeleteFile("testfile")                 ; Deleting works now

Re: Control if file is used before deletefile()

Posted: Tue May 28, 2019 11:58 am
by sinisrus
@JPV

Thank you very nice :-)

Re: Control if file is used before deletefile()

Posted: Tue May 28, 2019 5:49 pm
by airsoftsoftwair
Also note that this

Code: Select all

ExitOnError(False)
DeleteFile(file$)
code = GetLastError()
ExitOnError(True)
can be radically shortened to that now:

Code: Select all

code = ?DeleteFile(file$)

Re: Control if file is used before deletefile()

Posted: Tue May 28, 2019 11:24 pm
by sinisrus
@airsoftsoftwair

Ohh good :-)

This ? work with other function or only deletefile() ?

Re: Control if file is used before deletefile()

Posted: Wed May 29, 2019 9:39 pm
by airsoftsoftwair
sinisrus wrote:
Tue May 28, 2019 11:24 pm
@airsoftsoftwair
This ? work with other function or only deletefile() ?
Yes, it works with all functions. See here.