Writing Files in UnrealScript

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

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

class FileWriter extends Object;

// Helper function to check for errors
function CheckError(bool bSuccess)
{
    if (!bSuccess)
    {
        `log("An error occurred while writing to file");
    }
}

// Main function to demonstrate file writing
function WriteFiles()
{
    local string Content;
    local array<byte> ByteArray;
    local FileWriter Writer;
    local int BytesWritten;

    // To start, here's how to dump a string into a file.
    Content = "hello\nUnrealScript\n";
    class'FileManager'.static.SaveStringToFile(Content, "C:\\Temp\\dat1.txt");

    // For more granular writes, open a file for writing.
    Writer = new class'FileWriter';
    if (!Writer.OpenFile("C:\\Temp\\dat2.txt", FWRT_Text))
    {
        `log("Failed to open file for writing");
        return;
    }

    // You can write byte arrays as you'd expect.
    ByteArray.AddItem(115); // 's'
    ByteArray.AddItem(111); // 'o'
    ByteArray.AddItem(109); // 'm'
    ByteArray.AddItem(101); // 'e'
    ByteArray.AddItem(10);  // '\n'
    BytesWritten = Writer.WriteBinary(ByteArray.Length, ByteArray);
    `log("Wrote" @ BytesWritten @ "bytes");

    // WriteString is also available.
    BytesWritten = Writer.WriteString("writes\n");
    `log("Wrote" @ BytesWritten @ "bytes");

    // UnrealScript doesn't have a direct equivalent to bufio,
    // but we can simulate buffered writing by accumulating strings.
    Content = "buffered\n";
    BytesWritten = Writer.WriteString(Content);
    `log("Wrote" @ BytesWritten @ "bytes");

    // Close the file when done.
    Writer.CloseFile();
}

Try running the file-writing code in your UnrealScript environment.

Then check the contents of the written files:

$ type C:\Temp\dat1.txt
hello
UnrealScript

$ type C:\Temp\dat2.txt
some
writes
buffered

Note that UnrealScript’s file I/O capabilities are more limited compared to some other languages. It doesn’t have built-in buffering or flushing mechanisms, and file operations are often abstracted through the engine’s file system. The exact behavior and available functions may vary depending on the specific version of Unreal Engine you’re using.

Also, be aware that in a real game environment, you should use the appropriate game-specific paths and file access methods, as direct access to the file system might be restricted or not recommended for security reasons.