Writing Files in Julia

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

Our first example demonstrates how to write files in Julia. Writing files in Julia follows similar patterns to the ones we saw earlier for reading.

using Printf

function check(e)
    if e !== nothing
        throw(e)
    end
end

# To start, here's how to dump a string (or just bytes) into a file.
d1 = "hello\njulia\n"
open("/tmp/dat1", "w") do file
    write(file, d1)
end

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

# It's idiomatic to use a try-finally block to ensure the file is closed
try
    # You can write byte arrays as you'd expect.
    d2 = [0x73, 0x6f, 0x6d, 0x65, 0x0a]  # "some\n" in bytes
    n2 = write(f, d2)
    @printf("wrote %d bytes\n", n2)

    # A write for strings is also available.
    n3 = write(f, "writes\n")
    @printf("wrote %d bytes\n", n3)

    # Flush writes to ensure they're written to stable storage.
    flush(f)

    # Julia's IOBuffer provides buffered writing capabilities.
    buf = IOBuffer()
    n4 = write(buf, "buffered\n")
    @printf("wrote %d bytes\n", n4)

    # Use write to ensure all buffered operations have been applied to the underlying writer.
    write(f, take!(buf))
finally
    close(f)
end

Try running the file-writing code.

$ julia writing-files.jl
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

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