ID EN
Vector & List

connections

R Base 3.6.2

Functions to create, open and close connections, i.e., “generalized files”, such as possibly compressed files, URLs, pipes, etc.

Syntax

R
file(description = "", open = "", blocking = TRUE,
     encoding = getOption("encoding"), raw = FALSE,
     method = getOption("url.method", "default"))<p></p><p>url(description, open = "", blocking = TRUE,
    encoding = getOption("encoding"),
    method = getOption("url.method", "default"),
    headers = NULL)</p><p>gzfile(description, open = "", encoding = getOption("encoding"),
       compression = 6)</p><p>bzfile(description, open = "", encoding = getOption("encoding"),
       compression = 9)</p><p>xzfile(description, open = "", encoding = getOption("encoding"),
       compression = 6)</p><p>unz(description, filename, open = "", encoding = getOption("encoding"))</p><p>pipe(description, open = "", encoding = getOption("encoding"))</p><p>fifo(description, open = "", blocking = FALSE,
     encoding = getOption("encoding"))</p><p>socketConnection(host = "localhost", port, server = FALSE,
                 blocking = FALSE, open = "a+",
                 encoding = getOption("encoding"),
                 timeout = getOption("timeout"))</p><p>open(con, &#8230;)
# S3 method for connection
open(con, open = "r", blocking = TRUE, &#8230;)</p><p>close(con, &#8230;)
# S3 method for connection
close(con, type = "rw", &#8230;)</p><p>flush(con)</p><p>isOpen(con, rw = "")
isIncomplete(con)</p>

Arguments

Parameter Description
description character string. A description of the connection: see ‘Details’.
open character string. A description of how to open the connection (if it should be opened initially). See section ‘Modes’ for possible values.
blocking logical. See the ‘Blocking’ section.
encoding The name of the encoding to be assumed. See the ‘Encoding’ section.
raw logical. If true, a ‘raw’ interface is used which will be more suitable for arguments which are not regular files, e.g.character devices. This suppresses the check for a compressed file when opening for text-mode reading, and asserts that the ‘file’ may not be seekable.
method character string, partially matched to c("default", "internal", "wininet", "libcurl"): see ‘Details’.
headers named character vector of HTTP headers to use in HTTP requests. It is ignored for non-HTTP URLs. The User-Agent header, coming from the HTTPUserAgent option (see options) is used as the first header, automatically.
compression integer in 0--9. The amount of compression to be applied when writing, from none to maximal available. For xzfile can also be negative: see the ‘Compression’ section.
timeout numeric: the timeout (in seconds) to be used for this connection. Beware that some OSes may treat very large values as zero: however the POSIX standard requires values up to 31 days to be supported.
filename a filename within a zip file.
host character string. Host name for the port.
port integer. The TCP port number.
server logical. Should the socket be a client or a server?
con a connection.
type character string. Currently ignored.
rw character string. Empty or "read" or "write", partial matches allowed.
&#8230; arguments passed to or from other methods.

Return Value

file, pipe, fifo, url, gzfile, bzfile, xzfile, unz and socketConnection return a connection object which inherits from class "connection" and has a first more specific class. open and flush return NULL, invisibly. close returns either NULL or an integer status, invisibly. The status is from when the connection was last closed and is available only for some types of connections (e.g., pipes, files and fifos): typically zero values indicate success. Negative values will result in a warning; if wri

Details

The first nine functions create connections. By default the connection is not opened (except for a socketConnection), but may be opened by setting a non-empty value of argument open. For file the description is a path to the file to be opened or a complete URL (when it is the same as calling url), or "" (the default) or "clipboard" (see the ‘Clipboard’ section). Use "stdin" to refer to the C-level ‘standard input’ of the process (which need not be connected to anything in a console or embedded version of R, and is not in RGui on Windows). See also stdin() for the subtly different R-level concept of stdin. See nullfile() for a platform-independent way to get filename of the null device. For url the description is a complete URL including scheme (such as http://, https://, ftp:// or file://)

Examples

Example
R
# NOT RUN {
zzfil <- tempfile(fileext=".data")
zz <- file(zzfil, "w")  # open an output file connection
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(zzfil)
unlink(zzfil)

zzfil <- tempfile(fileext=".gz")
zz <- gzfile(zzfil, "w")  # compressed file
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
close(zz)
readLines(zz <- gzfile(zzfil))
close(zz)
unlink(zzfil)
zz # an invalid connection

zzfil <- tempfile(fileext=".bz2")
zz <- bzfile(zzfil, "w")  # bzip2-ed file
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
close(zz)
zz # print() method: invalid connection
print(readLines(zz <- bzfile(zzfil)))
close(zz)
unlink(zzfil)

## An example of a file open for reading and writing
Tpath <- tempfile("test")
Tfile <- file(Tpath, "w+")
c(isOpen(Tfile, "r"), isOpen(Tfile, "w")) # both TRUE
cat("abc\ndef\n", file = Tfile)
readLines(Tfile)
seek(Tfile, 0, rw = "r") # reset to beginning
readLines(Tfile)
cat("ghi\n", file = Tfile)
readLines(Tfile)
Tfile # -> print() :  "valid" connection
close(Tfile)
Tfile # -> print() :  "invalid" connection
unlink(Tpath)

## We can do the same thing with an anonymous file.
Tfile <- file()
cat("abc\ndef\n", file = Tfile)
readLines(Tfile)
close(Tfile)

# }
# NOT RUN {
## fifo example -- may hang even with OS support for fifos
if(capabilities("fifo")) {
  zzfil <- tempfile(fileext="-fifo")
  zz <- fifo(zzfil, "w+")
  writeLines("abc", zz)
  print(readLines(zz))
  close(zz)
  unlink(zzfil)
}
# }
# NOT RUN {
## Unix examples of use of pipes

# read listing of current directory
readLines(pipe("ls -1"))

# remove trailing commas.  Suppose
oldwd <- setwd(tempdir())
writeLines(c("450, 390, 467, 654,  30, 542, 334, 432, 421,",
"357, 497, 493, 550, 549, 467, 575, 578, 342,",
"446, 547, 534, 495, 979, 479"), "data2_")
% cat data2_
450, 390, 467, 654,  30, 542, 334, 432, 421,
357, 497, 493, 550, 549, 467, 575, 578, 342,
446, 547, 534, 495, 979, 479
# Then read this by
scan(pipe("sed -e s/,$// data2_"), sep = ",")
unlink("data2_"); setwd(oldwd)

# convert decimal point to comma in output: see also write.table
# both R strings and (probably) the shell need \ doubled
zzfil <- tempfile("outfile")
zz <- pipe(paste("sed s/\\\\./,/ >", zzfil), "w")
cat(format(round(stats::rnorm(48), 4)), fill = 70, file = zz)
close(zz)
file.show(zzfil, delete.file = TRUE)
# }
# NOT RUN {
## example for a machine running a finger daemon

con <- socketConnection(port = 79, blocking = TRUE)
writeLines(paste0(system("whoami", intern = TRUE), "\r"), con)
gsub(" *$", "", readLines(con))
close(con)
# }
# NOT RUN {
# }
# NOT RUN {
## Two R processes communicating via non-blocking sockets
# R process 1
con1 <- socketConnection(port = 6011, server = TRUE)
writeLines(LETTERS, con1)
close(con1)

# R process 2
con2 <- socketConnection(Sys.info()["nodename"], port = 6011)
# as non-blocking, may need to loop for input
readLines(con2)
while(isIncomplete(con2)) {
   Sys.sleep(1)
   z <- readLines(con2)
   if(length(z)) print(z)
}
close(con2)

## examples of use of encodings
# write a file in UTF-8
cat(x, file = (con <- file("foo", "w", encoding = "UTF-8"))); close(con)
# read a 'Windows Unicode' file
A <- read.table(con <- file("students", encoding = "UCS-2LE")); close(con)
# }

See Also

textConnection seek showConnections pushBack. Functions making direct use of connections are (text-mode) readLines writeLines cat sink scan parse read.dcf dput dump and (binary-mode) readBin readChar writeBin writeChar load and save. capabilities to see if fifo connections are supported by this build of R. gzcon to wrap gzip (de)compression around a connection. options HTTPUserAgent internet.info and timeout are used by some of the methods for URL connections. memCompress for more ways to (de)compress and references on data compression. extSoftVersion for the versions of the zlib (for gzfile) bzip2 and xz libraries in use. To flush output to the Windows and macOS consoles see flush.console.