Daniel Campos Daniel Campos - 1 year ago 142
R Question

How to close file connection in R after an error handle?

I have been using

function from read.dbc package and it is working fine for me.

Unfortunatelly, sometimes the file to be read is corrupted. To handle this, I use the try statement. The problem is that the corrupted file keeps "open" in R until I finish my R session, in a way I can't delete the file until the session is over.

My code is:

ReadFile <- try(read.dbc("C:/LocalPath/A_File.txt"))

Is there a way to "close" the connection prematurely (without the need to end the session)?

Also, I have tried to remove the variable with
and then cleaned the memory with
but the file keeps open.

More details: RStudio v0.99.484, R v3.3.1 (x64), OS Windows 7 Enterprise SP1

PS.: To reproduce the error simply try to read any file that is not a dbc file, a TXT file for example.

Answer Source

I don't think that this can be done in R as the file is locked from C code. If you look at the function dbc2dbf in this file you can see that it opens the file and tries to decompress it. Error "handling" is just printing the error and returning, but not closing the opened files which is bad practice imo. (Or a bug if you like to call it so.)

If you care you could open an issue on the github site of the project for this, maybe the author fixes the problem.

In case you are in desperate need (:P) of a working version I have compiled a quick fix for you that just calls fclose before it signals the error(s).

You can download it here. Just unpack and copy to your R library. Load with library(custom.read.dbc)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download