Saving persistent file on Android


I am trying to save a persistent file with settings on Android.
I use SDL_GetPrefPath which gives me “/data/data/”

Here’s my code with extras removed:

struct cfg {
} config;

//Determine config file.
char config_file[CONFIG_FILE_LEN];
char *path = SDL_GetPrefPath(“company”, “application”);
snprintf(config_file, CONFIG_FILE_LEN, “%sconfig.txt”, path);

//Write file
SDL_RWFromFile(config_file, “wb”);
size_t num = SDL_RWwrite(file, (void*)&config, sizeof(Config), 1);

//Read file
SDL_RWFromFile(config_file, “rb”);
size_t num = SDL_RWread(file, (void*)&config, sizeof(Config), 1);

Write returns 1, and seems successful.
On the next launch, the file seems to open (file is not NULL or 0), but read returns 0 objects.

I do not write or read anything else to this file, just dumping this one struct to it.

I have searched and searched and cannot find an answer to this. Help is much appreciated!

Thank you!

By the way, I have also added the following permission:

uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE”

It shouldn’t be necessary for the PrefPath, but I added it to rule this problem out. No difference.

Should sizeof(Config) be sizeof(config)?

Are you calling SDL_RWclose?

Have you checked what config_file actually contains?

Thank you.
The struct is actually defined as

typedef s truct config {
} Config;
Config config;

Thus sizeof(Config) should be good. I had stripped the code too much in my question.
This page won’t let me edit the question due to some permission, so I can’t fix it now.

However, I think the problem might have been that I wasn’t calling SDL_RWclose.

It seems to work after adding that.

Be wary when dumping structs to file and reading them back directly into the struct. What happens if you add a field to the struct? What happens if you change a type in the struct and the alignment of the other fields changes?

1 Like

When I save a file with my game’s data the first thing I write is an int with a version number. So every time I add a new variable I can code it to set that variable to a default value if an older version of the data file is loaded.

1 Like

Exactly what I do too. Thanks!

1 Like

It’s a larger dependency, but Google protobuf is really good at serializing complex structures with default values without requiring explicit versioning.