[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 22:32:43 CEST 2003


Professor Ripley,

Thanks for the quick response.  It is my understanding that "w+b" will open
a file for reading and writing but if a file with the same name already
exists then its contents are erased before the file is open.  So "w+b" is
not quite what I want.  I think I need "r+b".  And yes, I meant to seek the
*write* - sorry that I left off the rw argument to seek.  


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

>-----Original Message-----
>From: Prof Brian Ripley [mailto:ripley at stats.ox.ac.uk]
>Sent: Friday, April 25, 2003 1:18 PM
>To: STABLER Benjamin
>Cc: r-help at stat.math.ethz.ch
>Subject: Re: [R] Open an r+b file connection on Windows
>
>
>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