32
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") 
tumultous_rooster
  • 12,150
  • 32
  • 92
  • 149
Eva
  • 917
  • 4
  • 18
  • 23

1 Answers1

48

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.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
  • 4
    @hadley's comment is wise (unsurprisingly): prefer base behavior that's well-constructed to manage connections over dealing with them yourself. Having said that, I voted the above answer up for it's illustration of `on.exit`, for the general case where that wise advice doesn't apply. – Matt Tenenbaum Oct 15 '13 at 01:36
  • @MattTenenbaum : So if I open a file using `var1 <- readLines("filename.txt",encoding="UTF-8")`. I need not close it right? – discipulus Feb 15 '16 at 13:14