To write multiple data types to a file, you can use SDL_RWwrite()
for each type, ensuring you convert the data into a format that can be correctly interpreted when read back.
A common approach is to serialize the data, meaning you convert each piece of data into a sequence of bytes that can be written sequentially.
Here’s an example where we write both an integer and a string to a file:
#include <SDL.h>
#include <iostream>
#include <cstring>
namespace File {
void Write(const std::string& Path) {
SDL_RWops* Handle{
SDL_RWFromFile(Path.c_str(), "wb")
};
if (!Handle) {
std::cout << "Error opening file: "
<< SDL_GetError();
return;
}
int MyInt{42};
SDL_RWwrite(Handle, &MyInt,
sizeof(int), 1);
const char* MyString{"Hello World"};
size_t Length{strlen(MyString)};
SDL_RWwrite(Handle, &Length,
sizeof(size_t), 1);
SDL_RWwrite(Handle, MyString,
sizeof(char), Length);
SDL_RWclose(Handle);
}
}
Here’s what happens in the code:
SDL_RWwrite()
.When reading the data back, you'll need to perform these steps in reverse, first reading the integer, then the string length, and finally the string.
By carefully writing each data type in sequence, you can store complex structures in a single file. Just make sure that when you read the data back, you do so in the same order.
This approach works for many types, including structs, arrays, and more. For more complex data types, you may want to implement custom serialization logic.
Answers to questions are automatically generated and may not have been reviewed.
Learn to write and append data to files using SDL2's I/O functions.