6

I am struggling for quite some time with outputting a raw type to standard output. Here is what I tried and did not work the desired way:

r <- as.raw(c(0x41, 0x00, 0x43)) # r = "A\0C"
cat(rawToChar(r)) # displays warning and skips data after NULL (outputs "A")
cat(r) # outputs "41 00 43"
writeBin(r, stdout()) # error: can only write to binary connection

I am looking for a way to get all three bytes / characters printed to stdout.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
eold
  • 5,972
  • 11
  • 56
  • 75
  • It's sometimes possible to `writeBin(r, "/dev/stdout")` – Martin Morgan Sep 14 '11 at 22:41
  • Can you tell I'm bitter ;) ? I really wish R core would add a connections API. Then rApache could get rid of sendBin as Matt pointed out below. – Jeff Sep 15 '11 at 15:23
  • The original rationale might have been that the standard connections (i.e., stdin, stdout, and stderr) would always be connected to a text terminal (i.e., keyboard, terminal window). Hence, we have automatic text re-encoding, etc. Now that R has become a more general purpose language, it might be difficult to change that particular aspect without breaking something. A connections API would be helpful. – Matt Shotwell Sep 15 '11 at 21:12

1 Answers1

8

If you are using an operating system that has a 'cat' or similar program, we can pipe arbitrary data to stdout like so:

con <- pipe("cat", "wb")
writeBin(as.raw(c(0x41, 0x00, 0x43)), con)
flush(con)

This has been an issue for some time, especially because we would like to use R for common gateway interface (CGI). I don't believe there is a more direct route, but you might look at the RApache source code, to see how the sendBin function is implemented.

Matt Shotwell
  • 341
  • 1
  • 2