Add AutoFile::seek and tell

It's useful to be able to seek to a specific position in a file. Allow
AutoFile to seek by using fseek.

It's also useful to be able to get the current position in a file.
Allow AutoFile to tell by using ftell.
This commit is contained in:
Ava Chow 2024-01-02 16:34:50 -05:00
parent 23ba39470c
commit ca18aea5c4
2 changed files with 25 additions and 0 deletions

View file

@ -21,6 +21,28 @@ std::size_t AutoFile::detail_fread(Span<std::byte> dst)
}
}
void AutoFile::seek(int64_t offset, int origin)
{
if (IsNull()) {
throw std::ios_base::failure("AutoFile::seek: file handle is nullptr");
}
if (std::fseek(m_file, offset, origin) != 0) {
throw std::ios_base::failure(feof() ? "AutoFile::seek: end of file" : "AutoFile::seek: fseek failed");
}
}
int64_t AutoFile::tell()
{
if (IsNull()) {
throw std::ios_base::failure("AutoFile::tell: file handle is nullptr");
}
int64_t r{std::ftell(m_file)};
if (r < 0) {
throw std::ios_base::failure("AutoFile::tell: ftell failed");
}
return r;
}
void AutoFile::read(Span<std::byte> dst)
{
if (detail_fread(dst) != dst.size()) {

View file

@ -435,6 +435,9 @@ public:
/** Implementation detail, only used internally. */
std::size_t detail_fread(Span<std::byte> dst);
void seek(int64_t offset, int origin);
int64_t tell();
//
// Stream subset
//