Writing Data to Files

Writing Multiple Data Types to a File

How can I write multiple different data types (like integers and strings) to the same file?

Abstract art representing computer programming

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:

  1. We first write an integer to the file by passing its memory address and size to SDL_RWwrite().
  2. Next, we write the length of the string, which allows us to correctly read it back.
  3. Finally, we write the string itself.

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.

This Question is from the Lesson:

Writing Data to Files

Learn to write and append data to files using SDL2's I/O functions.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Writing Data to Files

Learn to write and append data to files using SDL2's I/O functions.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 62 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved