connection
file(description = "", open = "", blocking = TRUE, encoding = getOption("encoding")) In base R, a connection is a generalised file handle. It wraps plain files, gzip and bzip2 archives, ZIP members, URLs, shell pipes, FIFOs, TCP sockets, in-memory text buffers, and the console streams behind one object whose class starts with a subtype and inherits from "connection". The same set of methods (open, close, readLines, writeLines, cat, scan, seek) works against every source or sink.
A quick example: open a file in write mode, push two lines through cat(), close the handle, and read them back with readLines().
zz <- file("ex.data", "w")
cat("hello", "world", file = zz, sep = "\n")
close(zz)
readLines("ex.data")
# [1] "hello" "world"
unlink("ex.data")
That covers the most common pattern. The rest of this page walks through the constructors, methods, inspectors, and mode strings so you can read or write any source R supports.
Connection constructors
Every constructor lives in package base and returns an object whose class starts with a subtype and inherits from "connection". By default the handle is unopened; it opens on first I/O and closes again, or you can open it explicitly with open().
| Constructor | Returns | Notes |
|---|---|---|
file(description, open = "", blocking = TRUE, encoding = getOption("encoding"), raw = FALSE) | "file" handle | File path. Special values: "" opens an anonymous, unlinked temp file in "w+"; "stdin" reaches the C-level stdin; "clipboard" works on Windows and X11. |
url(description, open = "", blocking = TRUE, encoding = getOption("encoding"), method, headers) | "url" handle | Read-only. Supports http://, ftp://, and file://. |
gzfile(description, open = "", encoding = getOption("encoding"), compression = 6) | "gzfile" handle | Always binary underneath. Use "rt" if you want text-mode line-ending translation. |
bzfile(description, open = "", encoding = getOption("encoding"), compression = 9) | "bzfile" handle | Always binary underneath. Same text caveat as gzfile. |
unz(description, filename, open = "", encoding = getOption("encoding")) | "unz" handle | Read a single member from a .zip archive. Binary only. |
pipe(description, open = "", encoding = getOption("encoding")) | "pipe" handle | Shell command piped to or from R. |
fifo(description, open = "", blocking = FALSE, encoding = getOption("encoding")) | "fifo" handle | Named pipe. Unix only. Default blocking = FALSE. |
socketConnection(host = "localhost", port, server = FALSE, blocking = FALSE, open = "a+", encoding = getOption("encoding")) | "sockconn" handle | TCP socket. Default opens in "a+". |
The HTTPS scheme is not supported by url(). For HTTPS, use download.file(..., method = "libcurl") or a package such as httr, curl, or readr::url().
Standard connections
Three handles are pre-allocated when R starts and count against the 128-handle cap:
| Function | Returns |
|---|---|
stdin() | The R-console stdin (text, read-only). |
stdout() | The R-console stdout (text, write-only). |
stderr() | The R-console stderr (text, write-only). |
file("stdin") is not the same as stdin(): it reaches the C-level stdin of the process and depends on fdopen being available on the platform. nullfile() returns the OS null device ("/dev/null" on Unix, "nul:" on Windows), and isatty(con) reports whether a handle is wired to a terminal.
Test the standard streams quickly.
isatty(stdin()) # TRUE if R runs interactively
stdout() # the console output handle
nullfile() # "/dev/null" on Unix, "nul:" on Windows
Connection methods
These S3 methods work on any handle in the family:
| Method | Signature | Behaviour |
|---|---|---|
open(con, open = "r", blocking = TRUE, ...) | S3 on "connection" | Explicitly open. Default mode is read. |
close(con, type = "rw", ...) | S3 on "connection" | Close and release the underlying resource. |
flush(con) | Generic | Flush the write or append buffer where implemented. |
isOpen(con, rw = "") | Generic | Returns logical. rw can be "r" or "w" to test a specific direction. |
isIncomplete(con) | Generic | Returns logical. TRUE if the last read was a short block or output is unflushed. |
seek(con, where, rw = c("read", "write"), ...) | Generic | Move the read or write cursor. |
truncate(con, ...) | Generic | Truncate at the current position. |
print(x, ...) | S3 on "connection" | Prints class, description, and "valid" / "invalid". |
summary(x, ...) | S3 on "connection" | One-line state summary. |
Inspectors
showConnections(all = FALSE)
# class description mode text isopen can read can write
# [1,] "terminal" "stdin" "r" "text" "opened" "yes" "no"
# [2,] "terminal" "stdout" "w" "text" "opened" "no" "yes"
# [3,] "terminal" "stderr" "w" "text" "opened" "no" "yes"
showConnections() returns a character matrix of currently open user handles (use all = TRUE to include stdin, stdout, stderr, and any sink() diversions). getConnection(what) recovers the object for a row index, and closeAllConnections() closes every user handle and restores sink() diversions.
Mode strings
Not every mode applies to every type. Read + write and read + append are supported only by file() and socketConnection(). Compressed handles are always binary at the OS level; use "rt" for text translation on read.
| Mode | Meaning |
|---|---|
"r" or "rt" | Open for reading, text mode |
"w" or "wt" | Open for writing, text mode (truncates) |
"a" or "at" | Open for appending, text mode |
"rb" | Open for reading, binary |
"wb" | Open for writing, binary (truncates) |
"ab" | Open for appending, binary |
"r+", "r+b" | Read and write, no truncate |
"w+", "w+b" | Read and write, truncate first |
"a+", "a+b" | Read and append |
The default for every constructor except socketConnection is "", meaning “create but do not open”. R does not use the S default of "r+".
Examples
Write then read a file
The canonical first exercise: open a file for writing, push a few lines through cat(), close the handle, and read it back with readLines(). The comments under each call show what R prints when you run the snippet.
zz <- file("ex.data", "w")
cat("TITLE extra line", "2 3 5 7", "", "11 13 17",
file = zz, sep = "\n")
cat("One more line\n", file = zz)
close(zz)
readLines("ex.data")
# [1] "TITLE extra line" "2 3 5 7" "" "11 13 17" "One more line"
unlink("ex.data")
Read and write on the same connection
To do both on one file, open with "w+". That mode gives you read and write without reopening, but the cursor advances as you read or write, so you usually have to seek() it back to zero before you can read what you just wrote. Without that seek(), readLines() returns character(0) because the read cursor is sitting at the end of the file.
Tfile <- file("test1", "w+")
c(isOpen(Tfile, "r"), isOpen(Tfile, "w"))
# [1] TRUE TRUE
cat("abc\ndef\n", file = Tfile)
readLines(Tfile)
# character(0)
seek(Tfile, 0, rw = "r")
readLines(Tfile)
# [1] "abc" "def"
close(Tfile)
unlink("test1")
Gzipped output
gzfile() writes through gzip transparently. The on-disk file is binary, but readLines() on a text-mode "rt" handle does the line-ending translation for you. This is the easiest way to shrink a log without changing the rest of your I/O code.
zz <- gzfile("ex.gz", "w")
cat("a\nb\n", file = zz); close(zz)
readLines(zz <- gzfile("ex.gz"))
# [1] "a" "b"
close(zz); unlink("ex.gz")
Read shell output through a pipe
pipe() runs a shell command and exposes its stdout as a readable handle. Anything readLines(), scan(), or read.table() can do against a file, you can do against a command. This is faster than writing the output to a temp file and reading it back, and it avoids keeping an extra copy on disk.
readLines(pipe("ls -1"))
# [1] "DESCRIPTION" "NAMESPACE" "R" ...
Read a URL
url() works for plain HTTP, FTP, and file:// URLs. Read with readLines(), scan(), or read.table() exactly as you would for a local file, and remember to close() the handle when you are done. For HTTPS you need a different tool such as download.file(..., method = "libcurl") or httr.
con <- url("http://example.com", "r")
x <- readLines(con)
close(con)
Read from a text connection
textConnection() wraps an in-memory character vector so it looks like a file to functions that expect one. This is handy when you already have the data as lines and want to feed read.table() or read.csv() without writing to disk first.
lines <- c("name,score", "alice,9", "bob,7")
con <- textConnection(lines)
read.csv(con, stringsAsFactors = FALSE)
close(con)
# name score
# 1 alice 9
# 2 bob 7
Common gotchas
- Close your handles. Once a handle has no R reference, the garbage collector eventually closes it, but the timing is not guaranteed. Inside a function, prefer
on.exit(close(con))over relying on GC. - 128-handle cap. Three handles (stdin, stdout, stderr) are always taken. Stay well below the cap to avoid
"all the connections are in use". https://is not supported byurl(). Usedownload.file(..., method = "libcurl"),httr, orreadr::url().gzfile()andbzfile()are always binary underneath. Open with"rt"if you need text-mode line-ending translation.file()withdescription = ""opens an anonymous temp file in"w+"and unlinks it from disk. Useful for intermediate data that should never be visible by name.fifo()defaults toblocking = FALSE. Opening a non-blocking FIFO for writing only fails unless another process is already reading from it.- Text mode vs binary on Windows matters. On Unix the two are usually identical; on Windows, line endings are translated in text mode and passed through unchanged in binary mode.
closeAllConnections()also restoressink()diversions. Treat it as a safety net for long sessions, not a regular idiom.- Handles do not survive
save()/load()round trips. R serialises the wrapper object but not the underlying file descriptor, so a handle loaded on a different machine or after the file moved is invalid.