From 4d5feb0f3b052480250ecad7677d042e579fa538 Mon Sep 17 00:00:00 2001 From: apio Date: Tue, 24 Oct 2023 20:02:09 +0200 Subject: [PATCH] libos: Add File::seek() and File::tell() --- libos/include/os/File.h | 23 +++++++++++++++++++++++ libos/src/File.cpp | 14 ++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/libos/include/os/File.h b/libos/include/os/File.h index ccbd8061..ffef757a 100644 --- a/libos/include/os/File.h +++ b/libos/include/os/File.h @@ -37,6 +37,13 @@ namespace os ReadAppend = O_RDWR | O_APPEND, // Open the file read-write, and append to it. }; + enum class SeekMode + { + Beginning = SEEK_SET, // Seek from the beginning of the file. + Current = SEEK_CUR, // Seek from the current file position. + End = SEEK_END, // Seek from the end of the file. + }; + /** * @brief Create a new File object from a file path, opening the file. * @@ -191,6 +198,22 @@ namespace os */ void rewind(); + /** + * @brief Change the file pointer's position. + * + * @param offset The number of bytes to move the file pointer (can be negative, to move backwards). + * @param mode Where to seek from. + * @return Result Whether the operation succeeded. + */ + Result seek(off_t offset, SeekMode mode); + + /** + * @brief Read the file pointer's current position. + * + * @return Result An error, or the file pointer's position. + */ + Result tell(); + /** * @brief Buffering modes for a File. */ diff --git a/libos/src/File.cpp b/libos/src/File.cpp index 4b97c0b3..28421c50 100644 --- a/libos/src/File.cpp +++ b/libos/src/File.cpp @@ -227,6 +227,20 @@ namespace os fflush(m_file); } + Result File::seek(off_t offset, SeekMode mode) + { + int rc = fseek(m_file, offset, (int)mode); + if (rc < 0) return err(errno); + return {}; + } + + Result File::tell() + { + off_t off = ftell(m_file); + if (off < 0) return err(errno); + return off; + } + void File::set_buffer(BufferingMode mode) { setvbuf(m_file, NULL, mode, 0);