Skip to content

Commit ca18aea

Browse files
committed
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.
1 parent 23ba394 commit ca18aea

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/streams.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,28 @@ std::size_t AutoFile::detail_fread(Span<std::byte> dst)
2121
}
2222
}
2323

24+
void AutoFile::seek(int64_t offset, int origin)
25+
{
26+
if (IsNull()) {
27+
throw std::ios_base::failure("AutoFile::seek: file handle is nullptr");
28+
}
29+
if (std::fseek(m_file, offset, origin) != 0) {
30+
throw std::ios_base::failure(feof() ? "AutoFile::seek: end of file" : "AutoFile::seek: fseek failed");
31+
}
32+
}
33+
34+
int64_t AutoFile::tell()
35+
{
36+
if (IsNull()) {
37+
throw std::ios_base::failure("AutoFile::tell: file handle is nullptr");
38+
}
39+
int64_t r{std::ftell(m_file)};
40+
if (r < 0) {
41+
throw std::ios_base::failure("AutoFile::tell: ftell failed");
42+
}
43+
return r;
44+
}
45+
2446
void AutoFile::read(Span<std::byte> dst)
2547
{
2648
if (detail_fread(dst) != dst.size()) {

src/streams.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,9 @@ class AutoFile
435435
/** Implementation detail, only used internally. */
436436
std::size_t detail_fread(Span<std::byte> dst);
437437

438+
void seek(int64_t offset, int origin);
439+
int64_t tell();
440+
438441
//
439442
// Stream subset
440443
//

0 commit comments

Comments
 (0)