###--- >>> `connections' <<<----- Functions to Manipulate Connections

	## alias	 help(connections)
	## alias	 help(connection)
	## alias	 help(file)
	## alias	 help(pipe)
	## alias	 help(fifo)
	## alias	 help(gzfile)
	## alias	 help(url)
	## alias	 help(socketConnection)
	## alias	 help(open)
	## alias	 help(open.connection)
	## alias	 help(isOpen)
	## alias	 help(isIncomplete)
	## alias	 help(close)
	## alias	 help(close.connection)
	## alias	 help(print.connection)
	## alias	 help(summary.connection)
	## alias	 help(ISOLatin1)
	## alias	 help(MacRoman)
	## alias	 help(WinAnsi)
	## alias	 help(native.enc)

##___ Examples ___:

zz <- file("ex.data", "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("ex.data")
unlink("ex.data")

if(capabilities("libz")) {
  zz <- gzfile("ex.gz", "w")  # compressed file
  cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
  close(zz)
  print(readLines(gzfile("ex.gz")))
  unlink("ex.gz")
}

## An example of a file open for reading and writing
Tfile <- file("test1", "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)
close(Tfile)
unlink("test1")

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

if(capabilities("fifo")) {
  zz <- fifo("foo", "w+")
  writeLines("abc", zz)
  print(readLines(zz))
  close(zz)
  unlink("foo")
}

##Don't run: ## Unix examples of use of pipes
##D 
##D # read listing of current directory
##D readLines(pipe("ls -1"))
##D 
##D # remove trailing commas. Suppose
##D % cat data2
##D 450, 390, 467, 654,  30, 542, 334, 432, 421,
##D 357, 497, 493, 550, 549, 467, 575, 578, 342,
##D 446, 547, 534, 495, 979, 479
##D # Then read this by
##D scan(pipe("sed -e s/,$// data2"), sep=",")
##D 
##D # convert decimal point to comma in output
##D zz <- pipe(paste("sed s/\\./,/ >", "outfile"), "w")
##D cat(format(round(rnorm(100), 4)), sep = "\n", file = zz)
##D close(zz)
##D file.show("outfile", delete.file=TRUE)

##Don't run: ## example for Unix machine running a finger daemon
##D 
##D con <- socketConnection(port = 79, blocking = TRUE)
##D writeLines(paste(system("whoami", intern=TRUE), "\r", sep=""), con)
##D gsub(" *$", "", readLines(con))
##D close(con)

##Don't run: ## two R processes communicating via non-blocking sockets
##D # R process 1
##D con1 <- socketConnection(port = 6011, server=TRUE)
##D writeLines(LETTERS, con1)
##D close(con1)
##D 
##D # R process 2
##D con2 <- socketConnection(Sys.info()["nodename"], port = 6011)
##D # as non-blocking, may need to loop for input
##D readLines(con2)
##D while(isIncomplete(con2)) {Sys.sleep(1); readLines(con2)}
##D close(con2)

## Keywords: 'file', 'connection'.


