Alphish / gm-community-toolbox

A collection of utility functions for GameMaker.
MIT License
34 stars 6 forks source link

file_get_size #64

Closed Alphish closed 2 months ago

Alphish commented 6 months ago

For some reason, standard GM doesn't provide a simple function to get file size out fo the box. There's file_bin_size, but it requires opening a binary file for reading. Which I guess is acceptable, but still slightly unwieldy.

The proposed implementation would be:

/// @func file_get_size(filename)
/// @desc Retrieves the size of the file or -1, if the file doesn't exist or can't be read. Doesn't work on HTML5 target.
/// @arg {String} filename      The name of the file to get the size of.
function file_get_size(_filename) {
    // NOTE: file_bin_size doesn't work on HTML5, so throwing an exception here
    // GX.games target returns browser_not_a_browser target, so it doesn't get caught in this check
    if (os_browser != browser_not_a_browser)
        throw "The file size cannot be retrieved on the HTML5 target.";

    if (!file_exists(_filename))
        return -1;

    try {
        var _file = file_bin_open(_filename, /* mode: reading */ 0);
        var _size = file_bin_size(_file);
        file_bin_close(_file);
        return _size;
    } catch (_) {
        return -1
    }
}
Alphish commented 6 months ago

Nevermind, it's no faster than buffer_load, which becomes sort of misleading.