Keep file open throughout program execution vs open when needed and close

Viewed 52

I'm making a game, with a settings page, in C. I store these settings in a settings file. I have 2 options.

int WriteSettings(void) {
    FILE *File;
    return (memcmp(&Settings, &DefaultSettings, sizeof(struct SettingsStruct))? GetGameDir() && (File = fopen(SettingsPath, "w")) && fwrite(&Settings, sizeof(struct SettingsStruct), 1, File) == 1 && !fclose(File) : !unlink(SettingsPath))? 0 : AlertError("Unexpected error occurred while saving settings");
}

This code opens the settings file when needed, writes, and closes immediately or will delete the settings file if the data is identical to default. Another option is to keep the file open throughout game execution, and fwrite() and fflush() whenever the settings change and thus are saved. Which option is optimal?

1 Answers

nevilad:

Settings are typically changed by the user very rare, thus opening, writing and closing immediately would be better.

Related