How to access a file from res:// in the exported project

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By JensRenders

Hi,

I want to include an executable (stockfish) with my app, such that I can run it using OS.execute(). This works if I run the app from the editor. The problem is, I don’t understand how I can access this file once the app is exported, as res:// is not guaranteed to exist. I tried copying it to user://:

	DirAccess.copy_absolute("res://stockfish/stockfish_" + OS.get_name(), "user://stockfish/stockfish", 1777)

but this copy fails:

ERROR: Failed to open stockfish/stockfish_Linux
at: copy (core/io/dir_access.cpp:346)

It probably fails for the same reason: res:// does not exist? It does copy succesfully when I run it from the editor, and then I can indeed use it from user://. For the Android export I can look in the .apk and I see that stockfish/stockfish_Android is included, yet I get the same error. So if res:// is not accessible from the code, how do I get a file into user://? Or is there some other way to access a file?

Thanks a lot!

:bust_in_silhouette: Reply From: JensRenders

I found the solution. DirAccess does not work on files in res://, but FileAccess does. So I created this function that copies files from res:// to user:// by creating a new file in user:// and writing all the bytes form the file in res:// to it:

static func copy_from_res(from: String, to: String, chmod_flags: int=-1) -> void:
	var file_from = FileAccess.open(from, FileAccess.READ)
	var file_to = FileAccess.open(to, FileAccess.WRITE)
	file_to.store_buffer(file_from.get_buffer(file_from.get_length()))
	file_to = null
	file_from = null
	if chmod_flags != -1:
		var output = []
		OS.execute("chmod", [chmod_flags, ProjectSettings.globalize_path(to)], output, true)

The part about chmod_flags is there to control the permissions of the final file, just like in DirAccess.copy_absolute().

1 Like

unfortunately, in Exported project such as in Exported Windows game, the FileAccess and even DirAccess just failed to make a copy from res:// jpg file to a new target file.
i tested on Exported Windows Project, it just said:

USER SCRIPT ERROR: Attempt to call function 'get_length' in base 'null instance' on a null instance.
   at: copy_from_res

the error is because at this line

there’s just no resource file detected at file_from which is the res:// path for the resource we trying to copy
Have you tried Exported the game to windows?

Hi, this is because image files are actually imported into the .godot folder and the original files are not packaged on export. But the .jpg should be in the project still so you can use that to save an image.