Skip to content

Strange behaviour of read and writeBin

3 messages · Christian Ruckert, Jeff Ryan, Duncan Murdoch

#
To me it seems like writeBin() writes one char/byte more than expected.

 > con <- file("testbin", "wb")
 > writeBin("ttccggaa", con)
 > close(con)

 > con <- file("testbin", "rb")
 > readBin(con, what="character")
[1] "ttccggaa"
 > seek(con, what=NA)
[1] 9
 > close(con)

 > con <- file("testbin", "rb")
 > readBin(con, what="raw", n=20)
[1] 74 74 63 63 67 67 61 61 00
 > seek(con, what=NA)
[1] 9
 > close(con)

As the numbering starts with 0 the position should be 8 and not 9 after 
reading. There were two older threads which look very similar to my problem:

http://tolstoy.newcastle.edu.au/R/e2/devel/06/11/1119.html
http://r.789695.n4.nabble.com/Re-Problem-reading-binaries-created-with-fortran-More-infos-td974396.html

Thanks in advance,
Christian



 > sessionInfo()
R version 2.12.0 (2010-10-15)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
[1] C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] Biostrings_2.18.2 IRanges_1.8.8

loaded via a namespace (and not attached):
[1] Biobase_2.10.0
#
from ?seek

?seek? returns the current position (before any move), as a
     (numeric) byte offset from the origin, if relevant, or ?0? if not.

Your string is nul terminated (9 bytes long).  That would be the
current offset. If you only read one byte, you'd have to be more than
0 bytes offset.

Jeff

On Fri, Feb 4, 2011 at 4:35 AM, Christian Ruckert
<cruckert at uni-muenster.de> wrote:

  
    
#
On 04/02/2011 5:35 AM, Christian Ruckert wrote:
You want writeChar rather than writeBin to avoid the null termination of 
strings.

Duncan Murdoch