Refactor FILEIO

This commit is contained in:
kichikuou
2024-12-08 15:06:00 +09:00
parent 48d780add6
commit 8303f7c770
11 changed files with 229 additions and 313 deletions
+18 -84
View File
@@ -39,104 +39,50 @@ std::string FindFile(const std::string& dir, const char* filename) {
} // namespace
void FILEIO::SetSaveDir(const std::string& dir)
void FILEIO::set_savedir(const std::string& dir)
{
savedir = dir;
while (!savedir.empty() && savedir.back() == '/')
savedir.pop_back();
}
int FILEIO::StatSavedata(const char* filename, struct stat* buf)
int FILEIO::stat_save(const char* filename, struct stat* buf)
{
return stat(FindFile(savedir, filename).c_str(), buf);
}
FILEIO::~FILEIO(void)
{
if(fp != NULL) {
Fclose();
}
}
bool FILEIO::Fopen(const char *file_name, int mode)
{
mode_ = mode;
std::string path =
FindFile((mode & FILEIO_SAVEDATA) ? savedir : ".", file_name);
mode &= ~FILEIO_SAVEDATA;
if(fp != NULL) {
Fclose();
}
fp = NULL;
if(mode == FILEIO_READ_BINARY) {
fp = fopen(path.c_str(), "rb");
} else if(mode == FILEIO_WRITE_BINARY) {
fp = fopen(path.c_str(), "wb");
}
return (fp != NULL);
}
void FILEIO::Fclose()
{
if(fp) {
fclose(fp);
}
fp = NULL;
fclose(fp);
#ifdef __EMSCRIPTEN__
if (mode_ & FILEIO_WRITE_BINARY)
EM_ASM( xsystem35.shell.syncfs(); );
#endif
}
uint32 FILEIO::Fseek(long offset, int origin)
// static
std::unique_ptr<FILEIO> FILEIO::open(const char *file_name, int mode)
{
uint32 val = 0xFFFFFFFF;
if(origin == FILEIO_SEEK_CUR) {
val = fseek(fp, offset, SEEK_CUR);
} else if(origin == FILEIO_SEEK_END) {
val = fseek(fp, offset, SEEK_END);
} else if(origin == FILEIO_SEEK_SET) {
val = fseek(fp, offset, SEEK_SET);
std::string path =
FindFile((mode & FILEIO_SAVEDATA) ? savedir : ".", file_name);
mode &= ~FILEIO_SAVEDATA;
FILE* fp = NULL;
if(mode == FILEIO_READ_BINARY) {
fp = fopen(path.c_str(), "rb");
} else if(mode == FILEIO_WRITE_BINARY) {
fp = fopen(path.c_str(), "wb");
}
return val;
return fp ? std::unique_ptr<FILEIO>(new FILEIO(fp, mode)) : nullptr;
}
uint32 FILEIO::Ftell()
{
return ftell(fp);
}
size_t FILEIO::Fread(void* buffer, uint32 size, uint32 count)
{
return fread(buffer, size, count, fp);
}
size_t FILEIO::Fwrite(void* buffer, uint32 size, uint32 count)
{
return fwrite(buffer, size, count, fp);
}
int FILEIO::Fgetc()
{
return fgetc(fp);
}
int FILEIO::Fgetw()
{
int val = Fgetc();
return val | (Fgetc() << 8);
}
void FILEIO::Fgets(char *dest, int length)
void FILEIO::ag00_gets(char *dest, int length)
{
int p = 0;
for(;;) {
int c = Fgetc();
int c = getc();
if(c == 0x0d || c == EOF) {
break;
}
@@ -148,15 +94,3 @@ void FILEIO::Fgets(char *dest, int length)
}
dest[p] = '\0';
}
void FILEIO::Fputc(int c)
{
fputc(c, fp);
}
void FILEIO::Fputw(int w)
{
Fputc(w & 0xff);
Fputc((w >> 8) & 0xff);
}