fix save bug

This commit is contained in:
Hojun-Cho 2024-07-23 17:05:23 +09:00
parent 05a3ada827
commit 8c700685ab
3 changed files with 25 additions and 10 deletions

View File

@ -1,5 +1,5 @@
CC=tcc CC=tcc
CFLAGS= -c -Wall -g -Wextra CFLAGS= -Wall -g -Wextra -g
all: gb all: gb
@ -8,4 +8,4 @@ clean:
rm -f gb rm -f gb
gb: $(OBJ) gb: $(OBJ)
$(CC) jmp.S *.c -lSDL2 -o gb $(CC) jmp.S *.c -lSDL2 -o gb $(CFLAGS)

29
gb.c
View File

@ -3,11 +3,12 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include <fcntl.h>
int savereq, loadreq; int savereq, loadreq;
int cpuhalt; int cpuhalt;
int backup; int backup;
FILE *savefp; int savefd = -1;
int saveframes; int saveframes;
const char *romname; const char *romname;
u8 mbc, feat, mode; u8 mbc, feat, mode;
@ -22,11 +23,18 @@ writeback(void)
void void
flushback(void) flushback(void)
{ {
if(savefp != nil) if(savefd >= 0)
fwrite(back, 1, nback, savefp); pwrite(savefd, back, nback, 0);
saveframes = 0; saveframes = 0;
} }
static void
_flushback(void)
{
flushback();
close(savefd);
}
static void static void
loadsave(const char *file) loadsave(const char *file)
{ {
@ -38,16 +46,23 @@ loadsave(const char *file)
if(p == nil) if(p == nil)
p = buf + strlen(buf); p = buf + strlen(buf);
strcpy(p, ".sav"); strcpy(p, ".sav");
savefp = fopen(buf, "w+"); savefd = open(buf, O_RDWR);
if(savefp == 0){ if(savefd == -1){
savefd = open(buf, O_RDWR|O_CREAT, 0664);
if(savefd == -1)
error("Can't load save file '%s'", file); error("Can't load save file '%s'", file);
back = xalloc(nback);
if(write(savefd, back, nback)!= nback)
error("Can't Write %d byte to savefile", nback);
atexit(_flushback);
free(buf); free(buf);
return; return;
} }
back = xalloc(nback); back = xalloc(nback);
fwrite(back, 1, nback, savefp); if(read(savefd, back, nback) != nback)
error("savefile size is not matched\n");
atexit(_flushback);
free(buf); free(buf);
atexit(flushback);
} }
static void static void

BIN
zelda.sav Normal file

Binary file not shown.