Writing Files in Chapel

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

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

use IO;
use FileSystem;

proc check(e: Error) {
  if e != nil {
    halt(e);
  }
}

proc main() {
  // To start, here's how to dump a string (or just bytes) into a file.
  var d1 = b"hello\nchapel\n";
  try {
    var f = open("/tmp/dat1", iomode.cw);
    var writer = f.writer();
    writer.write(d1);
    writer.close();
  } catch e {
    check(e);
  }

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

  // It's idiomatic to use a try! block for file operations
  try! {
    // You can write byte arrays as you'd expect.
    var d2 = [115:uint(8), 111, 109, 101, 10];
    var n2 = f.writer().write(d2);
    writeln("wrote ", n2, " bytes");

    // A writeString method is also available.
    var n3 = f.writer().write("writes\n");
    writeln("wrote ", n3, " bytes");

    // Chapel doesn't have an explicit sync method, but closing the file
    // ensures all writes are flushed to stable storage.
    f.close();

    // Chapel doesn't have a built-in buffered writer, but you can implement
    // your own if needed. Here's a simple example using a string as a buffer.
    var buffer = "";
    buffer += "buffered\n";
    var n4 = buffer.length;
    writeln("wrote ", n4, " bytes");

    // Write the buffer to the file
    var f2 = open("/tmp/dat2", iomode.cw);
    f2.writer().write(buffer);
    f2.close();
  }
}

Try running the file-writing code.

$ chpl writing-files.chpl
$ ./writing-files
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

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