Writing Files in Crystal

Here’s the translation of the Go code to Crystal, formatted in Markdown suitable for Hugo:

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

require "file"

def check(e : Exception?)
  if e
    raise e
  end
end

# To start, here's how to dump a string (or just bytes) into a file.
d1 = "hello\ncrystal\n"
File.write("/tmp/dat1", d1, mode: 0o644)

# For more granular writes, open a file for writing.
File.open("/tmp/dat2", "w") do |f|
  # It's idiomatic to use a block when opening a file.
  # The file will be automatically closed when the block ends.

  # You can write byte slices as you'd expect.
  d2 = Bytes[115, 111, 109, 101, 10]
  n2 = f.write(d2)
  puts "wrote #{n2} bytes"

  # A write_string method is also available.
  n3 = f.write_string("writes\n")
  puts "wrote #{n3} bytes"

  # Issue a flush to ensure writes to stable storage.
  f.flush

  # Crystal's IO class provides buffered writers.
  f.buffered do |buf|
    n4 = buf.write_string("buffered\n")
    puts "wrote #{n4} bytes"
  end
  # The buffer is automatically flushed when the block ends.
end

Try running the file-writing code.

$ crystal writing-files.cr
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
crystal
$ 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.