src/fusion/ioutils

Search:
Group by:

Also defined in std/posix and system/io

Procs

proc duplicate(oldfd: FileHandle): FileHandle {....raises: [IOError], tags: [],
    forbids: [].}
Return a copy of the file handle oldfd. After a successful return, both FileHandle may be used interchangeably. They refer to the same open file description and share file offset and status flags. Calls POSIX function dup on Posix platform and _dup on Windows

Example:

# stdoutDuplicate is a copy of stdout FileHandle that points to STDOUT
let stdoutDuplicate = duplicate(stdout.getFileHandle())
# Writing to stdoutDuplicate will write to stdout
doAssert(stdoutDuplicate != stdout.getFileHandle())
# On windows, opening a file from a FileHandle does not work
when not defined(windows):
  var f : File
  let res = open(f, stdoutDuplicate, mode=fmWrite)
  let msg = "This is a test message that will be displayed ! \n"
  f.write(msg)
  # Output "Test"
  f.close()
proc duplicateTo(oldfd: FileHandle; newfd: FileHandle) {....raises: [IOError],
    tags: [], forbids: [].}
Perform the same task a duplicate but instead of using the lowest unused file descriptor it uses the FileHandle` specified by newfd. Calls POSIX function dup2 on Posix platform and _dup2 on Windows.

Example:

import os
# Redirect stdout to a file temporarily
let tmpFileName = getTempDir() / "hidden_output.txt"
let stdoutFileno = stdout.getFileHandle()
let stdoutDupFd = duplicate(stdoutFileno)

# Create a new file
let tmpFile: File = open(tmpFileName, fmAppend)
let tmpFileFd: FileHandle = tmpFile.getFileHandle()

# stdoutFileno now writes to tmpFile
duplicateTo(tmpFileFd, stdoutFileno)
echo "This is not displayed, but written to tmpFile instead !"

# Close file & restore stdout
tmpFile.close()
duplicateTo(stdoutDupFd, stdoutFileno)

# stdout is now restored !
echo "This is displayed"