[R] How to write the bytes 00 01 00 to a file/connection?

Henrik Bengtsson hb at maths.lth.se
Tue Jul 17 08:46:23 CEST 2001

Is there any way to write (8-bit) bytes to a file which works on all [R]
platforms? I have been looking at

  1) writeBin
  2) writeChar
  3) cat

and neither of them manage to write arbitrary sequences of bytes (0-255).

For instance, I would like to create a binary file of length three
containing the bytes 0, 1 and 0. I [R] I have the following vector of bytes:

  bfr <- c(0,1,0)

1) For having 'writeBin' to write bytes to a file the argument 'size' should
be one. However, this is not supported by my Windows Me system. I haven't
been able to try this on other platforms. Using 'writeBin(bfr, con)' with
default 'size' argument will generate a file containing 00 00 00 01 00 00,
i.e. two bytes for every integer. One approach would be to convert 8-bit
bytes into 16-bit integers and then write the integers. However, this would
only work for file sizes of even length!

Another approach is to convert the bytes to a vector of characters
"\000"-"\377", which in this case would be c("\000", "\001", "\000"). This
is possible and not too hard.

2) Using 'cat' to write strings will NOT work since it won't write "\000"'s.
Somewhere down the stream, the "\000"'s are cut of since they are interpret
as End of String. All other ASCII characters seems to work (I haven't tried
this fully on all systems though).

3) The third approach I tried was to use 'writeChar', which also can't write
"\000", except by using the 'eos' argument as eos="\000". This approach is
very awkward and requires a lot of ad-hoc coding and I am not sure it is
working the same on all platforms. Here is how you can write 00 01 00 to a

  fh <- file("writeChar.bin", "w")
  writeChar("", con=fh, nchars=0, eos="\000")
  writeChar("\001", con=fh, nchars=1, eos=NULL)
  writeChar("", con=fh, nchars=0, eos="\000")

If someone knows a better way of writing arbitrary byte sequences to a file,
please help me out.


Henrik Bengtsson
h b @ m a t h s . l t h . s e

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list