[R] Checking on closed file connections

Duncan Murdoch murdoch at stats.uwo.ca
Wed Jul 22 00:40:03 CEST 2009


On 21/07/2009 5:03 PM, Jim Nemesh wrote:
> Hi!  I'm wondering if there's a smart way around this:
> 
> fileName= (some valid file on your system)
> 
>  > 	fileCon=file(fileName, open="rt")
>  > 	l<-readLines (fileCon, n= 1)
>  >
>  > isOpen(fileCon)
> [1] TRUE
>  > 	close(fileCon)
>  > isOpen(fileCon)
> Error in isOpen(fileCon) : invalid connection
> 
> How do you test for a file being closed if isOpen gives you an error  
> message?

You could use try().

But you shouldn't be doing that.  Whoever opens the connection should 
close it.  The isOpen() test is designed to be used on newly created 
connections, being passed to some other function and guaranteed to be 
valid.  Was it created with file(fileName, open="rt") or file(fileName)? 
  That's what isOpen() is there to determine.  (The first one was 
opened, and should be closed by whoever opened it; the second one was 
not, and the function that uses it shouldn't leave it open.)

Duncan Murdoch




More information about the R-help mailing list