aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorAva Chow <github@achow101.com>2024-01-02 16:34:50 -0500
committerAva Chow <github@achow101.com>2024-04-01 14:37:24 -0400
commitca18aea5c4975ace4e307be96c74641d203fa389 (patch)
treeaf1fb649f9f10893d7a17f84369f973d40b7fa48 /src
parent23ba39470c3d155a65f0616f8848ada730658301 (diff)
downloadbitcoin-ca18aea5c4975ace4e307be96c74641d203fa389.tar.xz
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.
Diffstat (limited to 'src')
-rw-r--r--src/streams.cpp22
-rw-r--r--src/streams.h3
2 files changed, 25 insertions, 0 deletions
diff --git a/src/streams.cpp b/src/streams.cpp
index 6921dad677..cdd36a86fe 100644
--- a/src/streams.cpp
+++ b/src/streams.cpp
@@ -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()) {
diff --git a/src/streams.h b/src/streams.h
index bc04a2babd..57fc600646 100644
--- a/src/streams.h
+++ b/src/streams.h
@@ -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
//