[R] Can scan() detect end-of-file?

William Dunlap wdunlap at tibco.com
Thu Oct 15 22:16:58 CEST 2015


I would like to read a connection line by line with scan but
don't know how to tell when to quit trying.  Is there any
way that you can ask the connection object if it is at the end?

E.g.,

t <- 'A "Two line\nentry"\n\n"Three\nline\nentry" D E\n'
tfile <- tempfile()
cat(t, file=tfile)
tcon <- file(tfile, "r") # or tcon <- textConnection(t)
scan(tcon, what="", nlines=1)
#Read 2 items
#[1] "A"               "Two line\nentry"
> scan(tcon, what="", nlines=1)  # empty line
#Read 0 items
#character(0)
scan(tcon, what="", nlines=1)
#Read 3 items
#[1] "Three\nline\nentry" "D"                  "E"
scan(tcon, what="", nlines=1) # end of file
#Read 0 items
#character(0)
scan(tcon, what="", nlines=1) # end of file
#Read 0 items
#character(0)

I am reading virtual line by virtual line because the lines
may have different numbers of fields.

Bill Dunlap
TIBCO Software
wdunlap tibco.com



More information about the R-help mailing list