91 lines
1.9 KiB
C++
91 lines
1.9 KiB
C++
|
// Copyright 2024 The DMBMX2Tools Authors
|
||
|
// SPDX-License-Identifier: MIT
|
||
|
|
||
|
#include <base/io/FileStream.hpp>
|
||
|
#include <cstdio>
|
||
|
|
||
|
namespace dmtools::io {
|
||
|
|
||
|
constexpr auto DmToLibc(StreamSeekDirection dir) {
|
||
|
using enum StreamSeekDirection;
|
||
|
switch(dir) {
|
||
|
case Beg: return SEEK_SET;
|
||
|
case Cur: return SEEK_CUR;
|
||
|
case End: return SEEK_END;
|
||
|
default: return SEEK_SET;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
constexpr auto DmOpenMode(FileStream::OpenMode mode) {
|
||
|
using enum FileStream::OpenMode;
|
||
|
switch(mode) {
|
||
|
case Read: return "rb";
|
||
|
case ReadWrite: return "wb+";
|
||
|
}
|
||
|
}
|
||
|
|
||
|
FileStream::~FileStream() {
|
||
|
Close();
|
||
|
}
|
||
|
|
||
|
bool FileStream::Open(const std::string& filename, OpenMode mode) {
|
||
|
file = std::fopen(filename.c_str(), DmOpenMode(mode));
|
||
|
return Ok();
|
||
|
}
|
||
|
|
||
|
void FileStream::Flush() {
|
||
|
fflush(static_cast<std::FILE*>(file));
|
||
|
}
|
||
|
|
||
|
void FileStream::Close() {
|
||
|
if(Ok()) {
|
||
|
fclose(static_cast<std::FILE*>(file));
|
||
|
}
|
||
|
}
|
||
|
|
||
|
StreamDiff FileStream::ReadSome(u8* buffer, usize length) {
|
||
|
if(Ok())
|
||
|
return std::fread(static_cast<u8*>(buffer), 1, length, static_cast<std::FILE*>(file));
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
StreamDiff FileStream::WriteSome(const u8* buffer, usize length) {
|
||
|
if(Ok())
|
||
|
return std::fwrite(static_cast<const void*>(buffer), length, 1, static_cast<std::FILE*>(file));
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
StreamDiff FileStream::Seek(StreamDiff where, StreamSeekDirection dir) {
|
||
|
if(!Ok())
|
||
|
return -1;
|
||
|
|
||
|
#ifdef __GLIBC__
|
||
|
return fseeko64(static_cast<std::FILE*>(file), where, DmToLibc(dir));
|
||
|
#else
|
||
|
return fseek(static_cast<std::FILE*>(file), where, DmToLibc(dir));
|
||
|
#endif
|
||
|
}
|
||
|
|
||
|
StreamDiff FileStream::Tell() const {
|
||
|
if(!Ok())
|
||
|
return -1;
|
||
|
#ifdef __GLIBC__
|
||
|
return ftello64(static_cast<std::FILE*>(file));
|
||
|
#else
|
||
|
return ftell(static_cast<std::FILE*>(file));
|
||
|
#endif
|
||
|
}
|
||
|
|
||
|
bool FileStream::Ok() const {
|
||
|
return file != nullptr;
|
||
|
}
|
||
|
|
||
|
bool FileStream::Eof() const {
|
||
|
if(!Ok())
|
||
|
return true;
|
||
|
|
||
|
return feof(static_cast<std::FILE*>(file));
|
||
|
}
|
||
|
|
||
|
} // namespace dmtools::io
|