Writing Files in AngelScript

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

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

import std.file;
import std.string;

void check(bool success)
{
    if (!success)
    {
        print("An error occurred");
        exit(1);
    }
}

void main()
{
    // To start, here's how to dump a string (or just bytes) into a file.
    string content = "hello\nangelscript\n";
    bool success = file_put_contents("/tmp/dat1", content);
    check(success);

    // For more granular writes, open a file for writing.
    FILE@ f = fopen("/tmp/dat2", "w");
    check(f !is null);

    // It's good practice to close the file when we're done.
    defer(fclose(f));

    // You can write strings as you'd expect.
    string d2 = "some\n";
    int n2 = fwrite(d2, f);
    check(n2 == d2.length());
    print("wrote " + n2 + " bytes\n");

    // Another write example
    string d3 = "writes\n";
    int n3 = fwrite(d3, f);
    check(n3 == d3.length());
    print("wrote " + n3 + " bytes\n");

    // Flush writes to ensure they're written to disk.
    fflush(f);

    // AngelScript doesn't have built-in buffered writers,
    // but we can implement a simple one.
    BufferedWriter writer(f);
    int n4 = writer.write("buffered\n");
    print("wrote " + n4 + " bytes\n");

    // Flush the buffered writer to ensure all data is written.
    writer.flush();
}

class BufferedWriter
{
    BufferedWriter(FILE@ file)
    {
        @_file = file;
    }

    int write(const string &in data)
    {
        _buffer += data;
        if (_buffer.length() >= 1024)
        {
            flush();
        }
        return data.length();
    }

    void flush()
    {
        if (_buffer.length() > 0)
        {
            fwrite(_buffer, _file);
            _buffer = "";
        }
    }

    private FILE@ _file;
    private string _buffer;
}

Try running the file-writing code.

$ angelscript writing-files.as
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
angelscript

$ 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.