GameMaker: Recursive folder copying

In some situations you may want to copy a folder from your GameMaker game. And it would seem trivial but not that easy. file_copy can only copy files, and folder functions only allow you to create, check, and search folders for files. However, given these standard functions, implementing a folder copying routine is fairly easy.

Idea used here is to find a list of files and folders via file_find_*, and then go through them, checking whether they are files or folders, copying or recursively calling recursively function script accordingly. Sure that poses a potential problem if you were to copy entire disc contents to other location, but you are probably not going to be doing that via GameMaker... right?

Attached example contains the function and brief demonstration of functionality (you have to input source/destination paths as text).

Download GMK

Code follows,

/// file_copy_dir(source, target, attributes)
// Copies contents from source directory to target directory.
// Add fa_directory to attributes for recursive copying.
var fname, i, file, files, from, to;
// create directory if it doesn't exist yet:
if (!directory_exists(argument1)) directory_create(argument1)
// push matching files into array:
// (has to be done separately due to possible recursion)
files = 0
for (fname = file_find_first(argument0 + "/*.*", argument2); fname != ""; fname = file_find_next()) {
    // don't include current/parent directory "matches":
    if (fname == ".") continue
    if (fname == "..") continue
    // push file into array
    file[files] = fname
    files += 1
}
file_find_close()
// process found files:
i = 0
repeat (files) {
    fname = file[i]
    i += 1
    from = argument0 + "/" + fname
    to = argument1 + "/" + fname
    if (file_attributes(from, fa_directory)) { // note: in GM:S+, prefer directory_exists(from)
        file_copy_dir(from, to, argument2) // recursively copy directories
    } else {
        file_copy(from, to) // copy files as normal
    }
}

Related posts:

One thought on “GameMaker: Recursive folder copying

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.