[R] Open an r+b file connection on Windows

Benjamin.STABLER@odot.state.or.us Benjamin.STABLER at odot.state.or.us
Fri Apr 25 21:39:18 CEST 2003


I am trying to open an existing binary file, seek to a position in the
middle, and then write one byte, while keeping the already existing data
after that byte.  It seems to me that I am unable to open a connection to a
binary file in both read and write mode.  I can open the "r+b" binary file
connection and seek around, but I can't write to the file.  And looking at
the function definition for writeBin, it seems that writeBin automatically
creates a connection of type "wb" not what is specified by the R file
object.  I am working on Windows Nt 4.0 with R 1.7.  Any ideas?  Thanks in
advance.

#Create file
x<-1:50
myfile <- file("test","wb")
writeBin(as.real(x),myfile, 4)
close(myfile)

myfile <- file("test","r+b")
myfile
description       class        mode        text      opened    can read
can write 
     "test"      "file"       "r+b"    "binary"    "opened"       "yes"
"no"  

seek(myfile,where=40,origin="start")
readBin(myfile, real(), 10, 4)
[1] 11 12 13 14 15 16 17 18 19 20

#Write the number 99 to file
seek(myfile,where=40,origin="start")
writeBin(as.real(99),myfile, 4)

Error in writeBin(as.real(99), myfile, 4) : 
        cannot write to this connection

Benjamin Stabler
Transportation Planning Analysis Unit
Oregon Department of Transportation
555 13th Street NE, Suite 2
Salem, OR 97301  Ph: 503-986-4104



More information about the R-help mailing list