Reading Files in Nim

Our first example demonstrates reading files in Nim. Reading files is a common task in many programs. Let’s look at various ways to read files.

import std/[os, strutils]

# This helper function will streamline our error checks
proc check(e: bool) =
  if not e:
    raise newException(IOError, "An error occurred")

proc main() =
  # Read entire contents of a file into memory
  let dat = readFile("/tmp/dat")
  echo dat

  # For more control over reading, we can open the file
  var f = open("/tmp/dat")
  defer: f.close()  # Ensure file is closed when we're done

  # Read some bytes from the beginning of the file
  var b1 = newString(5)
  let n1 = f.readChars(b1)
  echo fmt"{n1} bytes: {b1[0..<n1]}"

  # Seek to a known location in the file and read from there
  f.setFilePos(6)
  var b2 = newString(2)
  let n2 = f.readChars(b2)
  echo fmt"{n2} bytes @ 6: {b2[0..<n2]}"

  # Seek relative to current position
  f.setFilePos(4, fspCur)

  # Seek relative to end of file
  f.setFilePos(-10, fspEnd)

  # Use readBuffer for more robust reading
  f.setFilePos(6)
  var b3 = newString(2)
  let n3 = f.readBuffer(addr b3[0], 2)
  echo fmt"{n3} bytes @ 6: {b3}"

  # Rewind to the beginning of the file
  f.setFilePos(0)

  # Use a buffered reader for efficiency with many small reads
  var line = ""
  if f.readLine(line):
    echo fmt"5 bytes: {line[0..<5]}"

# Run the main procedure
main()

To run this program, first create a test file:

$ echo "hello" > /tmp/dat
$ echo "nim" >> /tmp/dat
$ nim c -r reading_files.nim
hello
nim
5 bytes: hello
2 bytes @ 6: ni
2 bytes @ 6: ni
5 bytes: hello

This example demonstrates various ways to read files in Nim:

  1. Reading an entire file at once using readFile.
  2. Opening a file and reading chunks of data.
  3. Seeking to specific positions in the file.
  4. Using readBuffer for more robust reading.
  5. Using a buffered reader for efficient reading of small chunks.

Remember to always close files when you’re done with them. In Nim, we can use defer to ensure the file is closed when the procedure exits.

Next, we’ll look at writing files.