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

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Apr 25 22:17:32 CEST 2003


On Fri, 25 Apr 2003 Benjamin.STABLER at odot.state.or.us wrote:

> 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.  

Only if con is a character string, which it is not here ....

> 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"  

That is what is wrong:  try w+b (it's a bug, and I've fixed it for
R-devel).

> 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

Did you mean to seek the *write* here: you seek-ed the read position and 
so wrote at the beginning?  R connections have separate read and write 
positions.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list