#include "SDL_iostreamromfs.h"
static bool IsReadMode(const char *mode);
static bool HasPrefix(const char *file, const char *prefix);
static FILE *TryOpenFile(const char *file, const char *mode);
static FILE *TryOpenInRomfs(const char *file, const char *mode);
FILE *N3DS_FileOpen(const char *file, const char *mode)
{
if (!IsReadMode(mode)) {
return fopen(file, mode);
}
if (HasPrefix(file, "romfs:/") || HasPrefix(file, "sdmc:/")) {
return fopen(file, mode);
}
return TryOpenFile(file, mode);
}
static bool IsReadMode(const char *mode)
{
return SDL_strchr(mode, 'r') != NULL;
}
static bool HasPrefix(const char *file, const char *prefix)
{
return SDL_strncmp(prefix, file, SDL_strlen(prefix)) == 0;
}
static FILE *TryOpenFile(const char *file, const char *mode)
{
FILE *fp = NULL;
fp = TryOpenInRomfs(file, mode);
if (!fp) {
fp = fopen(file, mode);
}
return fp;
}
FILE *TryOpenInRomfs(const char *file, const char *mode)
{
FILE *fp = NULL;
char *prefixed_filepath = NULL;
if (SDL_asprintf(&prefixed_filepath, "romfs:/%s", file) < 0) {
return NULL;
}
fp = fopen(prefixed_filepath, mode);
SDL_free(prefixed_filepath);
return fp;
}