Writing Data to Files
Learn to write and append data to files using SDL2's I/O functions.
In this lesson, we'll introduce how to write data from our program to external sources. We'll focus on writing to files for now, but the techniques we cover lay the foundations for working with other data streams, such as network traffic.
As we might expect, SDL's mechanism for writing data shares much in common with their API for reading data. We'll rely on SDL_RWops
objects, and the functions we use will be familiar to what we learned in the previous lesson.
Like before, we'll start with a basic main
function that initializes SDL, and calls Write()
and Read()
functions within an included File
namespace.
// main.cpp
#include <SDL.h>
#include "File.h"
int main(int argc, char** argv) {
SDL_Init(0);
File::Write("output.txt");
File::Read("output.txt");
return 0;
}
Our Read()
function logs out the file's contents, using techniques we covered in the previous lesson. In this lesson, we'll work on the Write()
function, which is currently empty:
// File.h
#pragma once
#include <iostream>
#include <SDL.h>
namespace File {
void Read(const std::string& Path) {
char* Content{static_cast<char*>(
SDL_LoadFile(Path.c_str(), nullptr)
)};
if (Content) {
std::cout << "Content: " << Content;
} else {
std::cout << "Error loading file: "
<< SDL_GetError();
}
SDL_free(Content);
}
void Write(const std::string& Path) {
// ...
}
}
Running our program, we should see an error output from our Read()
function, as it's trying to read a file that we haven't created yet:
Error loading file: Parameter 'src' is invalid
Using SDL_RWFromFile()
We introduced the SDL_RWFromFile()
function in the previous lesson. It returns an SDL_RWops
object, which is SDL's standard interface for interacting with data streams, such as files.
In the previous lesson, we passed the file path and the "rb"
open mode to read the file. We'll use the same technique here, except we'll pass "wb"
as the open mode, as we want to write to the file. We cover open modes in more detail later in this lesson.
Let's update our File::Write()
function to create an SDL_RWops
handle for outputting content. Similar to the previous lesson, we'll also add an error check, and we'll close the file using SDL_RWclose()
when we're done:
// File.h
// ...
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();
}
// Use file...
SDL_RWclose(Handle);
}
}
The "wb"
open mode will additionally cause SDL to create a file if it doesn't exist. Therefore, running our program, after these changes we should now see our Read()
function can successfully open the file, although it has no content yet:
Content:
Using SDL_RWwrite()
The SDL_RWwrite()
function is one of the main ways we output a collection of objects or values to a file. Let's update our File::Write()
function to use it to output the C-style string "Hello World"
.
We introduced SDL_RWread()
in the previous lesson, and the arguments to SDL_RWwrite()
follow a similar pattern. It accepts 4 arguments:
- The
SDL_RWops
handle to use - A pointer to the memory address where the content we want to write begins. Remember, a C-style string is simply a location in memory containing a contiguous sequence of
char
values, represented by a pointer to the first character - achar*
. - The size of each object in bytes. In this example, we're writing
char
values, and achar
is1
byte. We could simply pass1
as the argument, but we'll usesizeof(char)
as it clarifies what the1
represents. - The quantity of objects to write. We can use the
strlen()
function to determine how many characters are in a C-style string
Let's update our File::Write()
function to make use of this:
// File.h
// ...
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();
}
const char* Content{"Hello World"};
SDL_RWwrite(Handle, Content,
sizeof(char), strlen(Content));
SDL_RWclose(Handle);
}
}
Content: Hello World
SDL_RWFromFile()
returns an integer, representing how many objects it wrote:
// File.h
// ...
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();
}
const char* Content{"Hello World"};
size_t ValuesWritten{SDL_RWwrite(
Handle, Content,
sizeof(char), strlen(Content)
)};
std::cout << ValuesWritten
<< " values written\n";
SDL_RWclose(Handle);
}
}
11 values written
Content: Hello World
We can add some simple error checking by comparing this return value to what we expected. As usual, we can call SDL_GetError()
for information on errors detected by SDL:
// File.h
// ...
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();
}
const char* Content{"Hello World"};
size_t ContentLength{strlen(Content)};
size_t ValuesWritten{SDL_RWwrite(
Handle, Content, sizeof(char),
ContentLength
)};
std::cout << ValuesWritten
<< " values written\n";
if (ValuesWritten < ContentLength) {
std::cout << "Expected " << ContentLength
<< " - Error: " << SDL_GetError() << '\n';
}
SDL_RWclose(Handle);
}
}
File Open Modes
In the previous lesson, we passed the rb
string, telling SDL (and ultimately the underlying platform) that we wanted to read from the file in binary mode. In this case, we're using wb
, indicating we want to create a new file for writing in binary mode.
If a file with the same name already exists, it will be entirely replaced when using wb
. We'll cover more open modes, including the ability to edit or add to an existing file later in this chapter.
Binary Mode vs Text Mode
Platforms typically offer two ways to read or write files. These are commonly called binary mode and text mode. Binary mode reads and writes data in the exact format provided. This is intended when the data is used to communicate between programs (or within the same program), where a consistent and predictable format is useful.
On the other hand, text mode performs some platform-specific transformations to format the file in a way that conforms to that platform's conventions.
For example, we use \n
to represent new lines in this course, but some platforms use a two-byte sequence: \r\n
. Text mode aims to handle those transformations. However, even if our program is writing data that is intended to be read by humans, that data is usually going to be read in some program that handles formatting, so binary mode is typically preferred even in that scenario.
As such, text mode is rarely useful, but can be used by removing the b
character from open modes if needed:
// Open a file for reading in text mode
SDL_RWFromFile("input.txt", "r")}
// Open a file for writing in text mode
SDL_RWFromFile("output.txt", "w")}
Adding to Existing Files
As we've seen, opening a file in "write" mode (such as "wb"
) ensures we get a new file every time we create our handle. If a file with that name already exists, it will be replaced.
In contrast, we can open a file in an "append" mode, such as "ab"
:
SDL_RWFromFile("some-file.txt", "ab")
This will also create the file if it doesn't exist yet. However, if it does exist, write operations will be done at the end of the existing file, preventing us from losing any of the existing data.
This is primarily useful for logging scenarios, where we want to keep track of the actions our program performed:
// main.cpp
#include <SDL.h>
#include "File.h"
int main(int argc, char** argv) {
SDL_Init(0);
File::Write("logs.txt", "One");
File::Write("logs.txt", "Two");
File::Write("logs.txt", "Three");
File::Read("logs.txt");
return 0;
}
// File.h
// ...
namespace File {
// ...
void Write(
const std::string& Path,
const char* Content
) {
SDL_RWops* Handle{
SDL_RWFromFile(Path.c_str(), "ab")};
if (!Handle) {
std::cout << "Error opening file: "
<< SDL_GetError();
}
SDL_RWwrite(
Handle, Content,
sizeof(char), strlen(Content)
);
SDL_RWclose(Handle);
}
}
Three file handles were opened and closed during the execution of the program, and each write operation was appended to the previous output:
Content: OneTwoThree
If we run our program again, the logging from the second execution will add more content to the file, without replacing the output of the previous execution:
Content: OneTwoThreeOneTwoThree
Writing Comma-Separated Values
Often when working with data files, we want to store multiple related values in a structured format. Comma-separated values (CSV) files are a common choice for this.
Let's extend our File
namespace to support writing multiple strings as CSV records. First, we'll create an overload of our Write()
function that accepts a vector of strings:
void Write(
const std::string& path,
const std::vector<std::string>& values
) {
SDL_RWops* Handle{
SDL_RWFromFile(path.c_str(), "wb")
};
if (!Handle) {
std::cout << "Error opening file: "
<< SDL_GetError();
return;
}
for (size_t i = 0; i < values.size(); ++i) {
const std::string& value = values[i];
SDL_RWwrite(Handle, value.c_str(),
sizeof(char), value.length());
// Add comma between values, newline at end
if (i < values.size() - 1) {
SDL_RWwrite(Handle, ",", sizeof(char), 1);
} else {
SDL_RWwrite(Handle, "\n", sizeof(char), 1);
}
}
SDL_RWclose(Handle);
}
We can use this new function like so:
std::vector<std::string> record{
"John", "Doe", "42", "Engineer"
};
File::Write("data.csv", record);
This will create a file containing:
John,Doe,42,Engineer
Writing Numeric Types
While we've focused on writing string data so far, often we need to write numeric values to files.
Since SDL_RWwrite()
works with raw memory, we'll need to convert our numbers to strings first if we want them to be human-readable. Here's a function that demonstrates this:
void WriteNumber(
const std::string& path,
auto number
) {
SDL_RWops* Handle{
SDL_RWFromFile(path.c_str(), "wb")
};
if (!Handle) {
std::cout << "Error opening file: "
<< SDL_GetError();
return;
}
// Convert number to string
std::string str = std::to_string(number);
SDL_RWwrite(Handle, str.c_str(),
sizeof(char), str.length());
SDL_RWclose(Handle);
}
Note that the auto
type in our number
parameter means WriteNumber
is a template function. We cover template functions in our advanced course but, for now, we can just note that it allows our function to be called with various numeric types:
File::WriteNumber("integer.txt", 42);
File::WriteNumber("float.txt", 3.14159f);
File::WriteNumber("double.txt", 2.71828);
This approach of converting a number to a string ensures our data is stored in a human-readable format. When we read these files back into our program, we can use string parsing functions like std::stoi()
, std::stof()
, or std::stod()
to convert these strings back to their numeric types like int
, float
and double
respectively.
We covered how to read numeric data in more detail in our previous lesson:
Reading Data from Files
Learn how to read and parse game data stored in external files using SDL_RWops
Serializing a Custom Object
Now that we know how to write strings and numbers to files, let's combine these techniques to serialize a simple class. We'll create a Player
class that contains both text and numeric data:
class Player {
public:
std::string name;
int level;
float health;
};
We can add serialization capabilities to this class within a SaveToFile()
method, using the same techniques we covered earlier in the lesson:
class Player {
public:
std::string name;
int level;
float health;
// Serialize the player to a file
void SaveToFile(const std::string& path) {
SDL_RWops* Handle{
SDL_RWFromFile(path.c_str(), "wb")
};
if (!Handle) {
std::cout << "Error opening file: "
<< SDL_GetError();
return;
}
// Convert numeric values to strings
std::string levelStr =
std::to_string(level);
std::string healthStr =
std::to_string(health);
// Write each value followed by a comma
SDL_RWwrite(Handle, name.c_str(),
sizeof(char), name.length());
SDL_RWwrite(Handle, ",",
sizeof(char), 1);
SDL_RWwrite(Handle, levelStr.c_str(),
sizeof(char), levelStr.length());
SDL_RWwrite(Handle, ",",
sizeof(char), 1);
SDL_RWwrite(Handle, healthStr.c_str(),
sizeof(char), healthStr.length());
SDL_RWclose(Handle);
}
};
We can use this class like so:
Player player{"Hero", 5, 100.0f};
player.SaveToFile("player.txt");
This will create a text file containing:
Hero,5,100.000000
Each piece of data is stored in a human-readable format, separated by commas. This approach makes the file easy to read and edit manually if needed.
A corresponding LoadFromFile()
function for this Player
class could look like this:
class Player {
public:
// ...
bool LoadFromFile(const std::string& path) {
// Load the entire file as a string
char* content{static_cast<char*>(
SDL_LoadFile(path.c_str(), nullptr)
)};
if (!content) {
std::cout << "Error loading file: "
<< SDL_GetError();
return false;
}
// Convert to a std::string for easier parsing
std::string data{content};
SDL_free(content);
// Find positions of commas
size_t firstComma = data.find(',');
size_t secondComma = data.find(',',
firstComma + 1);
if (firstComma == std::string::npos ||
secondComma == std::string::npos) {
std::cout << "Invalid file format\n";
return false;
}
// Extract and parse values
name = data.substr(0, firstComma);
std::string levelStr = data.substr(
firstComma + 1,
secondComma - firstComma - 1
);
std::string healthStr = data.substr(
secondComma + 1
);
try {
level = std::stoi(levelStr);
health = std::stof(healthStr);
} catch (const std::exception& e) {
std::cout << "Error parsing values: "
<< e.what() << '\n';
return false;
}
return true;
}
};
Summary
In this lesson, we explored writing data to files using SDL2 in C++. We learned how to:
- Create and open files using
SDL_RWFromFile()
- Write data to files with
SDL_RWwrite()
- Understand different file open modes, including binary and text modes
- Append data to existing files
- Handle potential errors during file operations
These skills form the foundation for more advanced file I/O operations in SDL2-based applications, which we'll build on through the rest of this chapter.
Numeric and Binary Data
Learn how C++ represents numbers and data in memory using binary, decimal, and hexadecimal systems.