Reading Files in AngelScript

Our first example demonstrates how to read files in AngelScript. Reading files is a common task in many programs. Let’s look at various ways to read file contents.

import std.io;
import std.string;

// Helper function to check for errors
void check(bool condition, const string& message) {
    if (!condition) {
        print("Error: " + message + "\n");
        exit();
    }
}

void main() {
    // Read entire file contents
    string dat = readFile("/tmp/dat");
    check(!dat.isEmpty(), "Failed to read file");
    print(dat);

    // Open file for more controlled reading
    file f;
    check(f.open("/tmp/dat", "r"), "Failed to open file");

    // Read some bytes from the beginning of the file
    array<uint8> b1(5);
    uint n1 = f.readBytes(b1);
    check(n1 > 0, "Failed to read bytes");
    print(n1 + " bytes: " + string(b1.substr(0, n1)) + "\n");

    // Seek to a known position and read from there
    f.seek(6);
    array<uint8> b2(2);
    uint n2 = f.readBytes(b2);
    check(n2 > 0, "Failed to read bytes");
    print(n2 + " bytes @ 6: " + string(b2) + "\n");

    // Seek relative to current position
    f.seek(4, SEEK_CUR);

    // Seek relative to end of file
    f.seek(-10, SEEK_END);

    // Read at least 2 bytes
    f.seek(6, SEEK_SET);
    array<uint8> b3(2);
    uint n3 = f.readBytes(b3);
    check(n3 >= 2, "Failed to read at least 2 bytes");
    print(n3 + " bytes @ 6: " + string(b3) + "\n");

    // Rewind to the beginning of the file
    f.seek(0, SEEK_SET);

    // Use a buffered reader for efficiency
    // Note: AngelScript doesn't have a built-in buffered reader,
    // so we'll simulate it with a larger read
    array<uint8> buffer(1024);
    uint bytesRead = f.readBytes(buffer);
    check(bytesRead > 0, "Failed to read buffer");
    print("First 5 bytes: " + string(buffer.substr(0, 5)) + "\n");

    // Close the file
    f.close();
}

To run this program, you would typically save it as a .as file and use an AngelScript interpreter or embed it in a host application that supports AngelScript.

Here’s an example of how you might prepare a file and run the script:

$ echo "hello" > /tmp/dat
$ echo "script" >> /tmp/dat
$ # Run the AngelScript file (method may vary based on your setup)
$ angelscript reading_files.as
hello
script
5 bytes: hello
2 bytes @ 6: sc
2 bytes @ 6: sc
First 5 bytes: hello

This example demonstrates various file reading techniques in AngelScript, including reading entire files, reading specific byte ranges, seeking to different positions in the file, and simulating buffered reading.

Note that AngelScript, being an embedded scripting language, may have different file I/O capabilities depending on the host application. The exact implementation might vary based on how AngelScript is integrated into your system.

In the next example, we’ll look at writing files.