Skip to content
Prev 25337 / 63424 Next

Clarification for readChar man page

Duncan Murdoch wrote:
Well, this is rather a misunderstanding on my part; I completely forgot 
about vectorization. The manual page makes sense to me now.

But the situation about the return value possibly being less than 
length(nchars) isn't clear. Consider a 101 byte text file in a 
non-multibyte character locale:

f <- tempfile()
writeChar(paste(rep(seq(0,9),10),collapse=''),con=f)

and calling readChar() to read 100 bytes with length(nchar)=10:

 > readChar(f,nchar=rep(10,10))
  [1] "0123456789" "0123456789" "0123456789" "0123456789" "0123456789"
  [6] "0123456789" "0123456789" "0123456789" "0123456789" "0123456789"

and readChar() reading the entire file with length(nchar)=11:

 > readChar(f,nchar=rep(10,11))
  [1] "0123456789" "0123456789" "0123456789" "0123456789" "0123456789"
  [6] "0123456789" "0123456789" "0123456789" "0123456789" "0123456789"
[11] "\0"

but the following two outputs are confusing. readchar() with 
length(nchar)>=12 returns a character vector length 12:

 > readChar(f,nchar=rep(10,12))
  [1] "0123456789" "0123456789" "0123456789" "0123456789" "0123456789"
  [6] "0123456789" "0123456789" "0123456789" "0123456789" "0123456789"
[11] "\0"         ""
 > readChar(f,nchar=rep(10,13))
  [1] "0123456789" "0123456789" "0123456789" "0123456789" "0123456789"
  [6] "0123456789" "0123456789" "0123456789" "0123456789" "0123456789"
[11] "\0"         ""

It seems that the first time EOF is encountered on a read operation, an 
empty string is returned, but on subsequent reads nothing is returned. 
Is this intended behavior?

Jeff