Skip to content

Commit

Permalink
COMMON: Set and implement a seekable base for file writer streams
Browse files Browse the repository at this point in the history
  • Loading branch information
Nostritius authored and DrMcCoy committed Jun 23, 2018
1 parent 630ad14 commit d148e86
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
20 changes: 19 additions & 1 deletion src/common/writefile.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,9 @@ size_t WriteFile::write(const void *dataPtr, size_t dataSize) {

assert(dataPtr);

const size_t oldPos = pos();
const size_t written = std::fwrite(dataPtr, 1, dataSize, _handle);
_size += written;
_size += MAX<size_t>(0, -size() + oldPos + written);

return written;
}
Expand All @@ -104,4 +105,21 @@ size_t WriteFile::size() const {
return _size;
}

size_t WriteFile::pos() const {
return std::ftell(_handle);
}

size_t WriteFile::seek(ptrdiff_t offset, SeekableWriteStream::Origin whence) {
const size_t oldPos = pos();
const size_t newPos = evalSeek(offset, whence, pos(), 0, size());

if (newPos > _size)
throw Exception(kSeekError);

if (std::fseek(_handle, newPos, SEEK_SET))
throw Exception(kSeekError);

return oldPos;
}

} // End of namespace Common
8 changes: 7 additions & 1 deletion src/common/writefile.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ namespace Common {
class UString;

/** A simple streaming file writing class. */
class WriteFile : boost::noncopyable, public WriteStream {
class WriteFile : boost::noncopyable, public SeekableWriteStream {
public:
WriteFile();
WriteFile(const UString &fileName);
Expand Down Expand Up @@ -66,6 +66,12 @@ class WriteFile : boost::noncopyable, public WriteStream {
/** Return the number of bytes written to the current file in total. */
size_t size() const;

/** Return the current position ot the stream in the file. */
size_t pos() const;

/** Seek to the speciied offset from the specified origin. */
size_t seek(ptrdiff_t offset, Origin whence = SeekableWriteStream::kOriginBegin);

protected:
std::FILE *_handle; ///< The actual file handle.

Expand Down

0 comments on commit d148e86

Please sign in to comment.