Warning: closing unused connection n

Eva picture Eva · Jun 10, 2011 · Viewed 48k times · Source
getCommentary=function(){
    Commentary=readLines(file("C:\\Commentary\\com.txt"))
    return(Commentary)
    close(readLines)
    closeAllConnections()
}

I have no idea what is wrong with this function. When I run this in R, it keeps giving me the following warning:

Warning message:
closing unused connection 5 ("C:\\Commentary\\com.txt") 

Answer

Gavin Simpson picture Gavin Simpson · Jun 10, 2011

readLines() is a function, you don't close() it. You want to close the connection opened by the file() function. Also, you are return()ing before you close any connections. As far as the function is concerned, the lines after the return() statement don't exist.

One option is to save the object returned by the file() call, as you shouldn't be closing all connections only those your function opens. Here is a non-function version to illustrate the idea:

R> cat("foobar\n", file = "foo.txt")
R> con <- file("foo.txt")
R> out <- readLines(con)
R> out
[1] "foobar"
R> close(con)

To write your function, however, I would probably take a slightly different tack:

getCommentary <- function(filepath) {
    con <- file(filepath)
    on.exit(close(con))
    Commentary <-readLines(con)
    Commentary
}

Which is used as follows, with the text file created above as an example file to read from

R> getCommentary("foo.txt")
[1] "foobar"

I used on.exit() so that once con is created, if the function terminates, for whatever reason, the connection will be closed. If you left this just to a close(con) statement just before the last line, e.g.:

    Commentary <-readLines(con)
    close(con)
    Commentary
}

the function could fail on the readLines() call and terminate, so the connection would not be closed. on.exit() would arrange for the connection to be closed, even if the function terminates early.