Writing Files in Nim

Here’s the translation of the Go code to Nim, with explanations in Markdown format suitable for Hugo:

Writing files in Nim follows similar patterns to the ones we saw earlier for reading.

import os, strutils

proc check(e: ref Exception) =
  if e != nil:
    raise e

proc main() =
  # To start, here's how to dump a string (or just bytes) into a file.
  let d1 = "hello\nnim\n"
  writeFile("/tmp/dat1", d1)

  # For more granular writes, open a file for writing.
  var f = open("/tmp/dat2", fmWrite)

  # It's idiomatic to defer a close immediately after opening a file.
  defer: f.close()

  # You can write byte sequences as you'd expect.
  let d2 = @[115'u8, 111, 109, 101, 10]
  let n2 = f.writeBytes(d2, 0, d2.len)
  echo "wrote ", n2, " bytes"

  # A write string is also available.
  let n3 = f.write("writes\n")
  echo "wrote ", n3, " bytes"

  # Issue a flush to ensure writes to stable storage.
  f.flushFile()

  # Nim's standard library provides buffered writers.
  var w = newFileStream(f, fmWrite)
  let n4 = w.write("buffered\n")
  echo "wrote ", n4, " bytes"

  # Use flush to ensure all buffered operations have been applied to the underlying writer.
  w.flush()

main()

Try running the file-writing code.

$ nim c -r writing_files.nim
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
nim
$ cat /tmp/dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin and stdout streams.