Add C function dup and dup2 posix to system/io (#15675)
* * Add handle to dup and dup2 posix as duplicate and duplicateTo in std/ioutils. * Added small test & changelog entry * Fixed import in tioutils removed when isMainModule * * Nest test inside block. Rename proc var -> let in captureStdout * Renamed tmpfile to iotuils.txt * Added block: # duplicate, duplicateTo * Improved docstring * Clean non-idiomatic code * Added runnable examples * rm 2 trailing space in expected output * Made syntax prettier * Runnable example: file in getTempDir() * Tmp -> Temp * Fixed runnableExamples on windows
This commit is contained in:
parent
066f3ebc2a
commit
12143d90c8
3 changed files with 136 additions and 1 deletions
49
tests/stdlib/tioutils.nim
Normal file
49
tests/stdlib/tioutils.nim
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
discard """
|
||||
output: '''
|
||||
hello1
|
||||
hello1
|
||||
'''
|
||||
"""
|
||||
|
||||
import std/ioutils
|
||||
import os
|
||||
from stdtest/specialpaths import buildDir
|
||||
|
||||
block: # duplicate, duplicateTo
|
||||
let tmpFileName = buildDir / "tioutils.txt"
|
||||
template captureStdout(body) : untyped =
|
||||
let stdoutFileno = stdout.getFileHandle()
|
||||
# Duplicate stoudFileno
|
||||
let stdout_dupfd = duplicate(stdoutFileno)
|
||||
# Create a new file
|
||||
# You can use append strategy if you'd like
|
||||
let tmpFile: File = open(tmpFileName, fmWrite)
|
||||
# Get the FileHandle (the file descriptor) of your file
|
||||
let tmpFileFd: FileHandle = tmpFile.getFileHandle()
|
||||
# dup2 tmpFileFd to stdoutFileno -> writing to stdoutFileno now writes to tmpFile
|
||||
duplicateTo(tmpFileFd, stdoutFileno)
|
||||
body
|
||||
# Force flush
|
||||
tmpFile.flushFile()
|
||||
# Close tmp
|
||||
tmpFile.close()
|
||||
# Read tmp
|
||||
let ret = readFile(tmpFileName)
|
||||
# Restore stdout
|
||||
duplicateTo(stdout_dupfd, stdoutFileno)
|
||||
ret
|
||||
|
||||
proc duplicateStdout() =
|
||||
var msg = "hello"
|
||||
echo msg & "1"
|
||||
|
||||
let s = captureStdout:
|
||||
echo msg & "2"
|
||||
|
||||
doAssert s == "hello2\n"
|
||||
|
||||
discard tryRemoveFile(tmpFileName)
|
||||
duplicateStdout()
|
||||
# Check it works twice
|
||||
duplicateStdout()
|
||||
doAssert tryRemoveFile(tmpFileName)
|
||||
Loading…
Add table
Add a link
Reference in a new issue