File I/O, OS and Processes

22.1 Files

Modes: fmRead, fmWrite, fmAppend, fmReadWrite, fmReadWriteExisting.

std/streams for a stream abstraction (newFileStream, newStringStream). std/memfiles for memory-mapped files.

writeFile("out.txt", "hello\n")
let content = readFile("out.txt")

let f = open("data.txt", fmWrite)
defer: f.close()
f.writeLine("line 1")
f.write("x = ", 42, "\n")

for line in lines("data.txt"): echo line

var fh: File
if open(fh, "data.txt"):
  while not fh.endOfFile: echo fh.readLine()
  fh.close()

22.2 Paths and Directories

import std/[os, paths]
echo getCurrentDir(), getHomeDir(), getTempDir(), getAppDir()
echo "dir" / "sub" / "file.txt"           # path join
echo splitFile("/a/b/c.txt")              # (dir, name, ext)
echo fileExists("x.txt"), dirExists("src")
createDir("build/out")
copyFile("a", "b"); moveFile("b", "c"); removeFile("c"); removeDir("build")
for kind, path in walkDir("."): echo kind, " ", path
for f in walkDirRec("src"): echo f
for f in walkFiles("*.nim"): echo f
echo getFileSize("x.txt"), getLastModificationTime("x.txt")

22.3 Environment and Command-Line

import std/[os, envvars, parseopt]
echo getEnv("HOME"), existsEnv("PATH")
putEnv("MY_VAR", "1")
echo paramCount(), " ", commandLineParams()
var p = initOptParser()
for kind, key, val in p.getopt():
  case kind
  of cmdLongOption, cmdShortOption: echo "opt ", key, "=", val
  of cmdArgument: echo "arg ", key
  of cmdEnd: discard
quit(QuitSuccess)

22.4 Running Processes

import std/osproc
let (output, code) = execCmdEx("git status")
echo code, output
discard execCmd("ls -la")
let p = startProcess("ping", args = ["-c", "3", "localhost"], options = {poUsePath, poStdErrToStdOut})
echo p.outputStream.readAll()
discard p.waitForExit()
p.close()