libpromeki main
PROfessional MEdia toolKIt
 
Loading...
Searching...
No Matches
File Class Reference

File I/O device with buffered reading. More...

#include <file.h>

Inheritance diagram for File:
Collaboration diagram for File:

Public Types

enum  Flags {
  NoFlags = 0x00 , Create = 0x01 , Append = 0x02 , Truncate = 0x04 ,
  Exclusive = 0x08
}
 File-specific open flags. More...
 
using FileHandle = int
 Platform-specific file handle type (POSIX).
 
- Public Types inherited from IODevice
enum  OpenMode {
  NotOpen = 0x00 , ReadOnly = 0x01 , WriteOnly = 0x02 , ReadWrite = ReadOnly | WriteOnly ,
  Append = 0x04 | WriteOnly
}
 Mode flags controlling how a device is opened. More...
 
- Public Types inherited from ObjectBase
using SlotVariantFunc = std::function< void(const VariantList &)>
 Function type for invoking a slot with a list of Variants.
 

Public Member Functions

 File (const File &)=delete
 Deleted copy constructor (non-copyable).
 
Fileoperator= (const File &)=delete
 Deleted copy assignment operator (non-copyable).
 
 File (ObjectBase *parent=nullptr)
 Default constructor. Creates a File with no filename.
 
 File (const String &fn, ObjectBase *parent=nullptr)
 Constructs a File with the given filename.
 
 File (const char *fn, ObjectBase *parent=nullptr)
 Constructs a File with the given C string filename.
 
 File (const FilePath &fp, ObjectBase *parent=nullptr)
 Constructs a File with the given file path.
 
 ~File ()
 Destructor. Closes the file if it is open.
 
const Stringfilename () const
 Returns the filename associated with this File.
 
void setFilename (const String &fn)
 Sets the filename.
 
int flags () const
 Returns the file-specific flags used at open time.
 
FileHandle handle () const
 Returns the native file handle.
 
Error open (OpenMode mode) override
 Opens the file with the given mode and no extra flags.
 
Error open (OpenMode mode, int fileFlags)
 Opens the file with the given mode and file-specific flags.
 
Error close () override
 Closes the file if it is open.
 
bool isOpen () const override
 Returns true if the file is currently open.
 
int64_t write (const void *data, int64_t maxSize) override
 Writes data to the file at the current position.
 
bool isSequential () const override
 Returns false (files are seekable).
 
Error seek (int64_t offset) override
 Seeks to an absolute byte offset.
 
int64_t pos () const override
 Returns the current read/write position.
 
Result< int64_tsize () const override
 Returns the total file size in bytes.
 
bool atEnd () const override
 Returns true if the position is at or past the end.
 
Result< int64_tseekFromCurrent (int64_t offset) const
 Seeks relative to the current file position.
 
Result< int64_tseekFromEnd (int64_t offset) const
 Seeks relative to the end of the file.
 
Error truncate (int64_t offset) const
 Truncates the file to the specified length.
 
Result< size_tdirectIOAlignment () const
 Returns the direct I/O alignment requirement for this file.
 
Error readBulk (Buffer &buf, int64_t size)
 Reads bulk data from the current file position using direct I/O.
 
Error setDirectIO (bool enable)
 Enables or disables direct I/O (bypass OS page cache).
 
bool isDirectIO () const
 Returns true if direct I/O is enabled.
 
Error setSynchronous (bool enable)
 Enables or disables synchronous writes.
 
bool isSynchronous () const
 Returns true if synchronous writes are enabled.
 
Error setNonBlocking (bool enable)
 Enables or disables non-blocking mode.
 
bool isNonBlocking () const
 Returns true if non-blocking mode is enabled.
 
- Public Member Functions inherited from BufferedIODevice
 BufferedIODevice (ObjectBase *parent=nullptr)
 Constructs a BufferedIODevice.
 
virtual ~BufferedIODevice ()
 Destructor.
 
int64_t read (void *data, int64_t maxSize) override
 Reads up to maxSize bytes into data.
 
int64_t bytesAvailable () const override
 Returns the number of bytes available for reading.
 
Error setReadBuffer (Buffer &&buf)
 Replaces the internal read buffer.
 
const BufferreadBuffer () const
 Returns a const reference to the current read buffer.
 
size_t readBufferSize () const
 Returns the capacity of the read buffer.
 
Buffer readLine (size_t maxLength=0)
 Reads a line of text up to a newline character.
 
Buffer readAll ()
 Reads all available data from the device.
 
Buffer readBytes (size_t maxBytes)
 Reads up to maxBytes bytes and returns as a Buffer.
 
bool canReadLine () const
 Returns true if a complete line is available for reading.
 
int64_t peek (void *buf, size_t maxBytes) const
 Reads up to maxBytes without consuming them.
 
Buffer peek (size_t maxBytes) const
 Reads up to maxBytes without consuming them.
 
void setUnbuffered (bool enable)
 Enables or disables unbuffered mode.
 
bool isUnbuffered () const
 Returns true if unbuffered mode is enabled.
 
- Public Member Functions inherited from IODevice
 IODevice (ObjectBase *parent=nullptr)
 Constructs an IODevice.
 
virtual ~IODevice ()
 Destructor.
 
virtual void flush ()
 Flushes any buffered output data to the underlying device.
 
virtual bool waitForReadyRead (unsigned int timeoutMs=0)
 Waits until data is available for reading or timeout.
 
virtual bool waitForBytesWritten (unsigned int timeoutMs=0)
 Waits until all pending data has been written or timeout.
 
OpenMode openMode () const
 Returns the current open mode.
 
bool isReadable () const
 Returns true if the device is readable.
 
bool isWritable () const
 Returns true if the device is writable.
 
Error error () const
 Returns the current error state.
 
void clearError ()
 Clears the error state to Ok.
 
 PROMEKI_SIGNAL (readyRead)
 Emitted when data is available for reading.
 
 PROMEKI_SIGNAL (bytesWritten, int64_t)
 Emitted when bytes have been written.
 
 PROMEKI_SIGNAL (errorOccurred, Error)
 Emitted when an error occurs.
 
 PROMEKI_SIGNAL (aboutToClose)
 Emitted just before the device is closed.
 
- Public Member Functions inherited from ObjectBase
 ObjectBase (ObjectBase *p=nullptr)
 Default ObjectBase constructor.
 
virtual ~ObjectBase ()
 Destructor. Emits aboutToDestroy, detaches from parent, and destroys children.
 
ObjectBaseparent () const
 Returns the parent object, if one. nullptr if none.
 
void setParent (ObjectBase *p)
 Sets the parent of this object. If the object already has a parent, it will be removed as a child from the old parent and added as a child to the new one.
 
const ObjectBaseListchildList () const
 Returns a list of children of this object.
 
template<typename... Args>
int registerSlot (Slot< Args... > *slot)
 Registers a slot with this object and assigns it an ID.
 
EventLoopeventLoop () const
 Returns the EventLoop this object is affiliated with.
 
void moveToThread (EventLoop *loop)
 Changes the EventLoop affinity of this object.
 
int startTimer (unsigned int intervalMs, bool singleShot=false)
 Starts a timer on this object's EventLoop.
 
void stopTimer (int timerId)
 Stops a timer previously started with startTimer().
 
template<typename... Args>
PROMEKI_NAMESPACE_BEGIN void connect (Signal< Args... > *signal, Slot< Args... > *slot)
 

Static Public Attributes

static constexpr FileHandle FileHandleClosedValue = -1
 Sentinel value representing a closed file handle (POSIX).
 
- Static Public Attributes inherited from ObjectBase
static constexpr const charaboutToDestroySignalName = PROMEKI_STRINGIFY( aboutToDestroy ) "(" PROMEKI_STRINGIFY_ARGS( ObjectBase * ) ")"
 
static SignalMeta aboutToDestroySignalMeta = SignalMeta(metaInfo(), aboutToDestroySignalName)
 

Protected Member Functions

int64_t readFromDevice (void *data, int64_t maxSize) override
 Reads raw data from the file descriptor.
 
int64_t deviceBytesAvailable () const override
 Returns bytes available from the device (file).
 
- Protected Member Functions inherited from BufferedIODevice
size_t bufferedBytesUnconsumed () const
 Returns the number of buffered bytes not yet consumed.
 
void ensureReadBuffer ()
 Ensures the read buffer is allocated.
 
void resetReadBuffer ()
 Resets the read buffer cursors.
 
- Protected Member Functions inherited from IODevice
void setOpenMode (OpenMode mode)
 Sets the open mode.
 
void setError (const Error &err)
 Sets the error state and emits errorOccurred.
 
- Protected Member Functions inherited from ObjectBase
ObjectBasesignalSender ()
 Returns the ObjectBase that emitted the signal currently being handled.
 
virtual void event (Event *e)
 Called by EventLoop to deliver events to this object.
 
virtual void timerEvent (TimerEvent *e)
 Called when a timer fires for this object.
 

Additional Inherited Members

- Static Public Member Functions inherited from ObjectBase
static const MetaInfometaInfo ()
 Returns the MetaInfo for the ObjectBase class.
 
template<typename... Args>
static void connect (Signal< Args... > *signal, Slot< Args... > *slot)
 connects a signal and slot together. This function assumes both the signal and slot exist in a ObjectBase or derived object
 
- Public Attributes inherited from ObjectBase
Signal< ObjectBase * > aboutToDestroySignal = Signal< ObjectBase * >(this, aboutToDestroySignalName)
 

Detailed Description

File I/O device with buffered reading.

Derives from BufferedIODevice, providing a full IODevice interface for file I/O. Supports direct I/O, synchronous writes, and non-blocking mode via setDirectIO(), setSynchronous(), and setNonBlocking().

File-specific open flags (Create, Append, Truncate, Exclusive) are passed via the open(OpenMode, int) overload. The IODevice open(OpenMode) overload opens with no extra flags.

When direct I/O is enabled, unbuffered mode is automatically forced. The previous unbuffered state is saved and restored when direct I/O is disabled.

Member Enumeration Documentation

◆ Flags

File-specific open flags.

These extend the IODevice OpenMode and are passed to open(OpenMode, int).

Enumerator
NoFlags 

No extra flags.

Create 

Create the file if it does not exist.

Append 

Append writes to the end of the file.

Truncate 

Truncate the file to zero length on open.

Exclusive 

Fail if the file already exists (with Create).

Constructor & Destructor Documentation

◆ File() [1/4]

File::File ( ObjectBase parent = nullptr)

Default constructor. Creates a File with no filename.

Parameters
parentThe parent object, or nullptr.

◆ File() [2/4]

File::File ( const String fn,
ObjectBase parent = nullptr 
)

Constructs a File with the given filename.

Parameters
fnThe path to the file.
parentThe parent object, or nullptr.

◆ File() [3/4]

File::File ( const char fn,
ObjectBase parent = nullptr 
)

Constructs a File with the given C string filename.

Parameters
fnThe path to the file.
parentThe parent object, or nullptr.

◆ File() [4/4]

File::File ( const FilePath fp,
ObjectBase parent = nullptr 
)

Constructs a File with the given file path.

Parameters
fpThe path to the file.
parentThe parent object, or nullptr.

Member Function Documentation

◆ atEnd()

bool File::atEnd ( ) const
overridevirtual

Returns true if the position is at or past the end.

Returns
true if at end of file.

Reimplemented from IODevice.

◆ close()

Error File::close ( )
overridevirtual

Closes the file if it is open.

Returns
Error::Ok on success, or an error if the close syscall fails.

Implements IODevice.

◆ deviceBytesAvailable()

int64_t File::deviceBytesAvailable ( ) const
overrideprotectedvirtual

Returns bytes available from the device (file).

Reimplemented from BufferedIODevice.

◆ directIOAlignment()

Result< size_t > File::directIOAlignment ( ) const

Returns the direct I/O alignment requirement for this file.

When the file is open, returns the filesystem block size via fstat. This is the alignment required for file offsets, buffer addresses, and transfer sizes when direct I/O is enabled.

Returns
A Result containing the alignment in bytes, or an error if the file is not open or fstat fails.

◆ filename()

const String & File::filename ( ) const
inline

Returns the filename associated with this File.

Returns
A const reference to the filename string.

◆ flags()

int File::flags ( ) const
inline

Returns the file-specific flags used at open time.

Returns
The Flags bitmask.

◆ handle()

FileHandle File::handle ( ) const
inline

Returns the native file handle.

Returns
The platform-specific file handle.

◆ isDirectIO()

bool File::isDirectIO ( ) const
inline

Returns true if direct I/O is enabled.

Returns
true if direct I/O is active.

◆ isNonBlocking()

bool File::isNonBlocking ( ) const
inline

Returns true if non-blocking mode is enabled.

Returns
true if non-blocking mode is active.

◆ isOpen()

bool File::isOpen ( ) const
overridevirtual

Returns true if the file is currently open.

Implements IODevice.

◆ isSequential()

bool File::isSequential ( ) const
overridevirtual

Returns false (files are seekable).

Reimplemented from IODevice.

◆ isSynchronous()

bool File::isSynchronous ( ) const
inline

Returns true if synchronous writes are enabled.

Returns
true if synchronous mode is active.

◆ open() [1/2]

Error File::open ( OpenMode  mode)
overridevirtual

Opens the file with the given mode and no extra flags.

Parameters
modeThe open mode (ReadOnly, WriteOnly, or ReadWrite).
Returns
Error::Ok on success, or an error on failure.

Implements IODevice.

◆ open() [2/2]

Error File::open ( OpenMode  mode,
int  fileFlags 
)

Opens the file with the given mode and file-specific flags.

Parameters
modeThe open mode (ReadOnly, WriteOnly, or ReadWrite).
fileFlagsA bitmask of Flags (Create, Append, Truncate, Exclusive).
Returns
Error::Ok on success, or an error on failure.

◆ pos()

int64_t File::pos ( ) const
overridevirtual

Returns the current read/write position.

Returns
The current position in bytes.

Reimplemented from IODevice.

◆ readBulk()

Error File::readBulk ( Buffer buf,
int64_t  size 
)

Reads bulk data from the current file position using direct I/O.

Reads size bytes from the current file position into buf, using direct I/O for the aligned interior of the region and normal I/O for any unaligned head and tail bytes. This is the optimal strategy for reading large media payloads (image data, audio samples) from container files, bypassing the OS page cache for the bulk transfer while handling misaligned boundaries gracefully.

This method calls shiftData() on buf so that the direct I/O portion lands on an aligned destination address. After a successful call, buf.data() points to the first byte of the requested payload. The caller only needs to ensure the buffer is allocated with at least directIOAlignment() alignment and that allocSize() is at least size + directIOAlignment():

size_t align = file.directIOAlignment();
Buffer buf(payloadSize + align, align);
Error err = file.readBulk(buf, payloadSize);
// buf.data() now points to the start of the payload
Generic memory buffer descriptor with alignment and memory space support.
Definition buffer.h:85
Lightweight error code wrapper for the promeki library.
Definition error.h:39
Dynamic array container wrapping std::vector.
Definition list.h:40

The buffer must be host-accessible and allocSize() must be large enough to accommodate the shift plus size bytes.

If the region is smaller than one alignment block, or if the alignment cannot be determined, a normal (non-DIO) read is used for the entire region. If direct I/O fails at runtime (e.g. the filesystem does not support O_DIRECT), the method falls back to normal I/O for that portion automatically.

If fewer than size bytes remain in the file, the read succeeds and buf.size() reflects the actual number of bytes read (which will be less than size).

Note
This method is not safe for use with non-blocking file descriptors. The underlying read loop treats EAGAIN as a hard error, which means a non-blocking fd that would block will cause readBulk to fail — and may lose already-read data from earlier portions of the transfer. If non-blocking bulk reads are needed, this will require a rework of the internal read loop.
Parameters
bufDestination buffer (must be host-accessible).
sizeNumber of bytes to read.
Returns
Error::Ok on success (check buf.size() for actual bytes read), or an appropriate error code.

◆ readFromDevice()

int64_t File::readFromDevice ( void data,
int64_t  maxSize 
)
overrideprotectedvirtual

Reads raw data from the file descriptor.

Implements BufferedIODevice.

◆ seek()

Error File::seek ( int64_t  offset)
overridevirtual

Seeks to an absolute byte offset.

Parameters
offsetThe byte offset to seek to.
Returns
Error::Ok on success, or an error on failure.

Reimplemented from IODevice.

◆ seekFromCurrent()

Result< int64_t > File::seekFromCurrent ( int64_t  offset) const

Seeks relative to the current file position.

Parameters
offsetThe byte offset relative to the current position.
Returns
A Result containing the new position, or an error.

◆ seekFromEnd()

Result< int64_t > File::seekFromEnd ( int64_t  offset) const

Seeks relative to the end of the file.

Parameters
offsetThe byte offset relative to the end (typically negative or 0).
Returns
A Result containing the new position, or an error.

◆ setDirectIO()

Error File::setDirectIO ( bool  enable)

Enables or disables direct I/O (bypass OS page cache).

When enabled, unbuffered mode is automatically forced on. When disabled, the previous unbuffered state is restored. If the file is open, the O_DIRECT flag is toggled via fcntl.

Parameters
enabletrue to enable direct I/O.
Returns
Error::Ok on success, or an error if the fcntl call fails.

◆ setFilename()

void File::setFilename ( const String fn)
inline

Sets the filename.

Only allowed when the file is not open.

Parameters
fnThe new filename.

◆ setNonBlocking()

Error File::setNonBlocking ( bool  enable)

Enables or disables non-blocking mode.

If the file is open, the O_NONBLOCK flag is toggled via fcntl.

Parameters
enabletrue to enable non-blocking operations.
Returns
Error::Ok on success, or an error if the fcntl call fails.

◆ setSynchronous()

Error File::setSynchronous ( bool  enable)

Enables or disables synchronous writes.

If the file is open, the O_SYNC flag is toggled via fcntl.

Parameters
enabletrue to enable synchronous writes.
Returns
Error::Ok on success, or an error if the fcntl call fails.

◆ size()

Result< int64_t > File::size ( ) const
overridevirtual

Returns the total file size in bytes.

Returns
A Result containing the file size, or an error if fstat fails.

Reimplemented from IODevice.

◆ truncate()

Error File::truncate ( int64_t  offset) const

Truncates the file to the specified length.

Parameters
offsetThe new file size in bytes.
Returns
Error::Ok on success, or an error on failure.

◆ write()

int64_t File::write ( const void data,
int64_t  maxSize 
)
overridevirtual

Writes data to the file at the current position.

Parameters
dataPointer to the data to write.
maxSizeNumber of bytes to write.
Returns
The number of bytes written, or -1 on error.

Implements IODevice.


The documentation for this class was generated from the following file: