To design a fast, robust, and cross-platform autosave system in C that supports multi-gigabyte files, is easy to integrate, and resists corruption, we adopt a modular and minimal architecture with a clean public interface. This system is intended for use within a client-server application, where each client maintains its own autosave state independently, and the autosave files are stored in a shared directory.
🧩 Architecture Overview
🧱 Core Components
-
Autosave Handle
- Encapsulates the autosave file path and temporary file path.
- Generated uniquely per client instance.
-
Autosave File Format
- A binary file with a header + data + checksum layout.
- Header contains metadata and a CRC32 checksum of the data.
-
CRC32 Implementation
- Internal implementation of CRC32 to ensure fast, portable checksums.
- Used to verify integrity of saved data.
-
Atomic Write Strategy
- Autosave writes are done to a temporary file, and only renamed to the final autosave file upon success.
- Ensures robustness and consistency.
-
Glib Integration
- Glib is used for:
- File I/O (
GFile, GInputStream, GOutputStream)
- Path manipulation
- Error handling via
GError
-
Cross-Platform Considerations
- File paths and naming are handled with Glib utilities.
- Temporary file creation and atomic rename are abstracted via Glib.
📦 Public Interface
#ifndef AUTOSAVE_H
#define AUTOSAVE_H
#include <glib.h>
#include <stdint.h>
/**
* @brief Handle for managing autosave operations.
*/
typedef struct {
gchar *autosave_path;
gchar *tempfile_path;
} AutosaveHandle;
/**
* @brief Initializes the autosave system for a given base file.
*
* @param base_file_path Path to the original model file.
* @param error Optional error output.
* @return AutosaveHandle* Handle for subsequent autosave operations, or NULL on failure.
*/
AutosaveHandle* autosave_init(const char* base_file_path, GError** error);
/**
* @brief Saves the given data to the autosave file.
*
* @param handle Autosave handle initialized via autosave_init.
* @param data Pointer to the data buffer to save.
* @param size Size of the data buffer.
* @param error Optional error output.
* @return gboolean TRUE on success, FALSE on failure.
*/
gboolean autosave_save(AutosaveHandle* handle, const void* data, size_t size, GError** error);
/**
* @brief Loads the autosaved data into memory.
*
* @param handle Autosave handle initialized via autosave_init.
* @param data_out Pointer to the output data buffer (allocated internally).
* @param size_out Pointer to the output data size.
* @param error Optional error output.
* @return gboolean TRUE on success, FALSE on failure.
*/
gboolean autosave_load(AutosaveHandle* handle, void** data_out, size_t* size_out, GError** error);
/**
* @brief Checks if an autosave file exists for the current client.
*
* @param handle Autosave handle initialized via autosave_init.
* @param error Optional error output.
* @return gboolean TRUE if autosave file exists, FALSE otherwise.
*/
gboolean autosave_exists(AutosaveHandle* handle, GError** error);
/**
* @brief Cleans up the autosave handle and releases resources.
*
* @param handle Autosave handle to free.
*/
void autosave_cleanup(AutosaveHandle* handle);
#endif // AUTOSAVE_H
📁 Autosave File Format
Each autosave file is a binary file structured as follows:
[Header (fixed size)] [Data (variable size)] [Checksum (4 bytes)]
Header Structure
typedef struct {
uint32_t magic; // Magic number "ASV1" (4 bytes)
uint32_t version; // Version (4 bytes)
uint64_t data_size; // Size of the data block (8 bytes)
uint32_t checksum_type; // Type of checksum (e.g., CRC32 = 1) (4 bytes)
uint8_t checksum[4]; // Checksum of the data (4 bytes)
} AutosaveHeader;
🧮 Checksum Implementation
A fast and compact CRC32 implementation is used for checksums. It should be included in the autosave module as crc32.c and crc32.h.
uint32_t crc32(const void* data, size_t length);
This function is used to compute the checksum of the data before saving and to verify it during loading.
🧪 Robustness and Corruption Detection
- Atomic Writes: Autosave writes are done to a temporary file and only renamed to the final autosave file after a successful write and
fsync.
- Checksum Validation: Upon load, the checksum is recomputed and compared with the stored value.
- Truncation Detection: The file is checked for unexpected truncation by comparing the declared data size with the actual read size.
🧩 Uniqueness of Autosave Files
Each client instance generates a unique autosave filename based on:
- Base file path
- PID (Process ID)
- Timestamp (in microseconds)
- Random number (for extra uniqueness)
This ensures that multiple clients operating on the same base file can maintain separate autosave states.
Example filename:
model.dat.autosave.12345_1698765432_123456
🧰 Usage Example
#include "autosave.h"
int main() {
GError* error = NULL;
AutosaveHandle* handle = autosave_init("model.dat", &error);
if (!handle) {
g_printerr("Failed to initialize autosave: %s\n", error->message);
return 1;
}
// Assume data is a pointer to a large buffer
void* data = malloc(1024 * 1024 * 1024); // 1 GB
size_t size = 1024 * 1024 * 1024;
// Populate data...
if (!autosave_save(handle, data, size, &error)) {
g_printerr("Failed to autosave: %s\n", error->message);
}
void* loaded_data;
size_t loaded_size;
if (!autosave_load(handle, &loaded_data, &loaded_size, &error)) {
g_printerr("Failed to load autosave: %s\n", error->message);
}
free(data);
free(loaded_data);
autosave_cleanup(handle);
return 0;
}
✅ Key Features Summary
| Feature | Description |
|---|
| Cross-Platform | Uses Glib for file I/O and path handling. |
| Robustness | Atomic writes prevent partial writes; checksums detect corruption. |
| Large File Support | Efficient binary format and memory management support gigabyte-sized data. |
| Multi-Client Support | Unique autosave files per client; safe to run multiple instances. |
| Easy Integration | Minimal API; no need for complex setup or threading. |
| Lightweight Design | No unnecessary abstractions or dependencies beyond Glib and standard C. |
📌 Conclusion
This autosave system is designed to be fast, robust, and easy to integrate into an existing C-based client-server application. It uses Glib for cross-platform compatibility and ensures data integrity through checksums and atomic writes. The architecture is clean, modular, and avoids over-engineering, making it ideal for performance-sensitive, large-scale applications.