util/io: add SDL_RWsync function

This function is meant to flush any internal buffers and (hopefully)
ensure the data has reached its ultimate destination (e.g. a file on
disk) before returning. This is currently implemented as a crude hack
and only supports stdio-based RWops. It calls fflush() on the internal
FILE* pointer, and on POSIX-systems it also calls fsync() on the file
descriptor.
This commit is contained in:
Andrei Alexeyev 2022-07-12 01:31:47 +03:00
parent b9fb06843d
commit 1191b239bc
No known key found for this signature in database
GPG key ID: 72D26128040B9690
2 changed files with 23 additions and 0 deletions

View file

@ -16,6 +16,10 @@
#include "rwops/rwops_autobuf.h"
#include "util/crap.h"
#ifdef TAISEI_BUILDCONF_HAVE_POSIX
#include <unistd.h>
#endif
char *SDL_RWgets(SDL_RWops *rwops, char *buf, size_t bufsize) {
char c, *ptr = buf, *end = buf + bufsize - 1;
assert(end > ptr);
@ -177,3 +181,21 @@ void *SDL_RWreadAll(SDL_RWops *rwops, size_t *out_size, size_t max_size) {
}
}
}
void SDL_RWsync(SDL_RWops *rwops) {
#if HAVE_STDIO_H
if(rwops->type == SDL_RWOPS_STDFILE) {
FILE *fp = rwops->hidden.stdio.fp;
if(UNLIKELY(!fp)) {
return;
}
fflush(fp);
#ifdef TAISEI_BUILDCONF_HAVE_POSIX
fsync(fileno(fp));
#endif
}
#endif
}

View file

@ -16,6 +16,7 @@ char *SDL_RWgets(SDL_RWops *rwops, char *buf, size_t bufsize) attr_nonnull_all;
char *SDL_RWgets_realloc(SDL_RWops *rwops, char **buf, size_t *bufsize) attr_nonnull_all;
size_t SDL_RWprintf(SDL_RWops *rwops, const char* fmt, ...) attr_printf(2, 3) attr_nonnull_all;
void *SDL_RWreadAll(SDL_RWops *rwops, size_t *out_size, size_t max_size) attr_nonnull_all;
void SDL_RWsync(SDL_RWops *rwops);
// This is for the very few legitimate uses for printf/fprintf that shouldn't be replaced with log_*
void tsfprintf(FILE *out, const char *restrict fmt, ...) attr_printf(2, 3);