SDL
1/*
2Simple DirectMedia Layer
3Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
4
5This software is provided 'as-is', without any express or implied
6warranty. In no event will the authors be held liable for any damages
7arising from the use of this software.
8
9Permission is granted to anyone to use this software for any purpose,
10including commercial applications, and to alter it and redistribute it
11freely, subject to the following restrictions:
12
131. The origin of this software must not be misrepresented; you must not
14claim that you wrote the original software. If you use this software
15in a product, an acknowledgment in the product documentation would be
16appreciated but is not required.
172. Altered source versions must be plainly marked as such, and must not be
18misrepresented as being the original software.
193. This notice may not be removed or altered from any source distribution.
20*/
21
22#include "SDL_iostreamromfs.h"23
24// Checks if the mode is a kind of reading
25static bool IsReadMode(const char *mode);26
27// Checks if the file starts with the given prefix
28static bool HasPrefix(const char *file, const char *prefix);29
30static FILE *TryOpenFile(const char *file, const char *mode);31static FILE *TryOpenInRomfs(const char *file, const char *mode);32
33/* Nintendo 3DS applications may embed resources in the executable. The
34resources are stored in a special read-only partition prefixed with
35'romfs:/'. As such, when opening a file, we should first try the romfs
36unless sdmc is specifically mentioned.
37*/
38FILE *N3DS_FileOpen(const char *file, const char *mode)39{
40// romfs are read-only41if (!IsReadMode(mode)) {42return fopen(file, mode);43}44
45// If the path has an explicit prefix, we skip the guess work46if (HasPrefix(file, "romfs:/") || HasPrefix(file, "sdmc:/")) {47return fopen(file, mode);48}49
50return TryOpenFile(file, mode);51}
52
53static bool IsReadMode(const char *mode)54{
55return SDL_strchr(mode, 'r') != NULL;56}
57
58static bool HasPrefix(const char *file, const char *prefix)59{
60return SDL_strncmp(prefix, file, SDL_strlen(prefix)) == 0;61}
62
63static FILE *TryOpenFile(const char *file, const char *mode)64{
65FILE *fp = NULL;66
67fp = TryOpenInRomfs(file, mode);68if (!fp) {69fp = fopen(file, mode);70}71
72return fp;73}
74
75FILE *TryOpenInRomfs(const char *file, const char *mode)76{
77FILE *fp = NULL;78char *prefixed_filepath = NULL;79
80if (SDL_asprintf(&prefixed_filepath, "romfs:/%s", file) < 0) {81return NULL;82}83
84fp = fopen(prefixed_filepath, mode);85
86SDL_free(prefixed_filepath);87return fp;88}
89