On 21/07/2009 8:13 PM, Jim Nemesh wrote:
On Jul 21, 2009, at 6:40 PM, Duncan Murdoch wrote:
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
The story is of course slightly more complicated. I'm writing a
streaming caching file input class. When you instantiate the class,
you open a connection (as shown in the sample code.) I wanted to
close the file input when either a) I run out of lines in the file b)
when the class is garbage collected. There's something fishy going on
with the connection, as it always claims to be invalid when I try to
close it, yet it reads data out perfectly fine.
Essentially, I'm always getting warnings about not closing the file,
but I can't close the file!
Some paired down "real world" code (using R.oo Library)
I don't have anything against R.oo, but I really don't know it at all.
So you're on your own with this one.
Duncan Murdoch
setConstructorS3("StreamingFileReader", function(fileName) {
if (missing (fileName)) fileName =NA
extend(Object(), "StreamingFileReader",
.fileName=fileName,
.fileCon=NA,
.initialized=F)
})
setMethodS3("init", "StreamingFileReader", function(this, ...){
if (this$.initialized==F) {
this$.fileCon=file(this$.fileName, open="rt")
#read header
if (this$.hasHeader) {
l<-readLines (this$.fileCon, n= 1)
l<-strsplit (l, '\t')[[1]]
this$.header=l
}
this$.initialized=T
}
})
setMethodS3("getHeader", "StreamingFileReader", function(this,
numLines=1, ...) {
this$init()
return (this$.header);
})
#lots of attempts to remove, cleanup, etc the connection I'm holding
on to.
setMethodS3("finalize", "StreamingFileReader", function(this, ...) {
#if (this$.hasMoreData==F) return()
#if (is.na(this$.fileCon)) return()
#rm (this$.fileCon)
#print (isOpen(this$.fileCon))
#close(this$.fileCon)
#close(this$.fileCon)
})
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.