Glusoft

Using the Filesystem API with SDL3

Get the base path

const char* base_path = SDL_GetBasePath();
SDL_Log("Base path: %s", base_path);

Get the preference path

char* pref_path = SDL_GetPrefPath("MyCompany", "MyApp");
SDL_Log("Pref path: %s", pref_path);

Get the current diectory

char* cwd = SDL_GetCurrentDirectory();
SDL_Log("Current directory: %s", cwd);

Get user folder

const char* documents = SDL_GetUserFolder(SDL_FOLDER_DOCUMENTS);
if (documents) {
    SDL_Log("User Documents folder: %s", documents);
}

Create a test directory

We must first allocate a buffer large enough to handle the concatenation of strings

const char* base_path = SDL_GetBasePath();
char cwd2[128];
strcpy( cwd2, cwd );
const char * dir_name = strcat(cwd2, "test_dir");
SDL_CreateDirectory(dir_name);

Create a test file

char cwd3[128];
strcpy( cwd3, cwd );
const char* file_path = strcat(cwd3, "/test_dir/test_file.txt");
SDL_IOStream* file = SDL_IOFromFile(file_path, "w");
if (file) {
    SDL_WriteIO(file, "Hello SDL3", 10);
    SDL_CloseIO(file);
}

Duplicate a file

char cwd4[128];
strcpy( cwd4, cwd );
const char* file_path_copy = strcat(cwd4, "test_dir/test_file_copy.txt");
SDL_CopyFile(file_path, file_path_copy);

Iterate over a directory

SDL_EnumerationResult callback(void *userdata, const char *dirname, const char *fname) {
    SDL_Log("  - %s (%s)", fname, dirname);
    return SDL_ENUM_CONTINUE;
}
int count = SDL_EnumerateDirectory(dir_name, callback, NULL);

Pattern match files inside a directory

int match_count;
char ** matches = SDL_GlobDirectory(dir_name, "*.txt", 0, &match_count);
SDL_Log("Matching .txt files: %d", match_count);
SDL_free(matches);

Get path informations

// Get path info SDL_PathInfo path_info; if (SDL_GetPathInfo(file_path, &path_info)) { SDL_Log("Path Info for %s:", file_path); }

Rename a file

cwd5[128];
strcpy( cwd5, cwd );
const char* file_path_renamed = strcat(cwd5, "test_dir/test_file_renamed.txt");
SDL_RenamePath(file_path_copy, file_path_renamed);

Remove a file

SDL_RemovePath(file_path_renamed);

Download the full project : Handling Keyboard and Mouse Events with SDL3

Need another OS ? => Windows, Mac, Linux