How to open a file called `stdin` in R? ... but not actual "standard input"

Viewed 47

How do I open a file called stdin in R? In other words, how to create a connection using file() to an actual file called stdin instead of actually reading from standard input?

Here specifically, I do not want to open "standard input", but a file named stdin.

I know I can open a file called file.txt in R like so:

#!/usr/bin/env Rscript
input <- file("file.txt", "r")
l <- readLines(input, n=1)
cat(l)
cat("\n")

When running, the above script prints the first line of the file correctly:

$ cat ./stdin
first line
second line

$ Rscript program.r 
first line

However, when I try to open a file called stdin, R seems to take input from the actual standard input (keyboard / redirect):

...
input <- file("stdin", "r")
...

The above tries to take keyboard input:

$ Rscript program.r 
asdf  # my keyboard input
asdf  # output of the script

$ echo test | Rscript program.r 
test

How to actually open a file called stdin?

1 Answers

The string "stdin" is sort of a reserved word in file() that means opening standard input (keyboard/pipe/redirect). To open a connection to an actual "stdin" file, you can use "./stdin" as an argument to file(), like so:

#!/usr/bin/env Rscript
input <- file("./stdin", "r")
l <- readLines(input, n=1)
cat(l)
cat("\n")

The above code successfully prints the first line of a file called stdin:

$ cat ./stdin
first line
second line

$ Rscript program.r
first line

There are other reserved file names for file(), here's an incomplete list:

  • stdin: standard input (keyboard);
  • stdout: standard output (terminal screen);
  • stderr: standard error output (terminal screen).

Again, to open actual files with the above names, prefix them with ./.

(This was tested on R 4.1.3)

Related