To enable saving the configuration back to a file, we need to add a Save()
method to our Config
class.
This method will do the reverse of Load()
: it will take the current values of the Config
object's members and write them to a file in the correct format.
Save()
Here's how we can implement the Save()
method:
#include <SDL.h>
#include <iostream>
#include <string>
#include <vector>
class Config {
public:
std::string WindowTitle;
int WindowWidth;
int WindowHeight;
std::vector<int> Levels;
void Save(const std::string& Path) {
SDL_RWops* File{SDL_RWFromFile(
Path.c_str(), "w")};
if (!File) {
std::cout << "Failed to open config file "
"for writing: " << SDL_GetError() << "\n";
return;
}
std::string Content{""};
Content += "WINDOW_TITLE: "
+ WindowTitle + "\n";
Content += "WINDOW_WIDTH: "
+ std::to_string(WindowWidth) + "\n";
Content += "WINDOW_HEIGHT: "
+ std::to_string(WindowHeight) + "\n";
Content += "LEVELS: ";
for (size_t i{0}; i < Levels.size(); ++i) {
Content += std::to_string(Levels[i]);
if (i < Levels.size() - 1) {
Content += ",";
}
}
Content += "\n";
SDL_RWwrite(
File,
Content.c_str(),
Content.size(),
1
);
SDL_RWclose(File);
}
};
int main() {
Config MyConfig;
MyConfig.WindowTitle = "My Awesome Game";
MyConfig.WindowWidth = 1024;
MyConfig.WindowHeight = 768;
MyConfig.Levels = {1, 2, 3, 4, 5};
MyConfig.Save("config.txt");
}
WINDOW_TITLE: My Awesome Game
WINDOW_WIDTH: 1024
WINDOW_HEIGHT: 768
LEVELS: 1,2,3,4,5
SDL_RWFromFile()
for Writing: We use SDL_RWFromFile()
with the "w" mode to open the file for writing. If the file doesn't exist, it will be created. If it does exist, it will be overwritten.Content
String: We create a std::string
called Content
and build it up line by line, using +
to append each key-value pair. We use std::to_string()
to convert numeric values to strings.SDL_RWwrite()
: We use SDL_RWwrite()
to write the entire Content string to the file.SDL_RWclose()
: We close the file using SDL_RWclose()
.In your game, you might modify the Config
object's properties during gameplay (e.g., the player changes settings in a menu).
Then, you can call Save("config.txt")
to save the updated configuration to the file, making the changes persistent across game sessions.
Answers to questions are automatically generated and may not have been reviewed.
std::string
Learn how to read, parse, and use config files in your game using std::string
and SDL_RWops