Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions |

# QIODevice Class Reference

The QIODevice class is the base interface class of all I/O devices in Qt. More...

    #include <QIODevice>

Inherits QObject.

Inherited by Q3Socket, Q3SocketDevice, QBuffer, QFile, QProcess, and QAbstractSocket.

Note: All the functions in this class are reentrant.

- List of all members, including inherited members
- Obsolete members

### Public Types

- typedef OpenMode
- enum OpenModeFlag { NotOpen, ReadOnly, WriteOnly, ReadWrite, Append, ..., Unbuffered }

### Writable Properties

- 1 writable property inherited from QObject

### Public Functions

- QIODevice ()
- QIODevice ( QObject * parent )
- virtual ~QIODevice ()
- virtual bool atEnd () const
- virtual Q_LONGLONG bytesAvailable () const
- virtual Q_LONGLONG bytesToWrite () const
- virtual bool canReadLine () const
- virtual void close ()
- QString errorString () const
- virtual bool flush ()
- bool getChar ( char * c )
- bool isOpen () const
- bool isReadable () const
- virtual bool isSequential () const
- bool isWritable () const
- virtual bool open ( OpenMode mode )
- OpenMode openMode () const
- virtual Q_LONGLONG pos () const
- bool putChar ( char c )
- Q_LONGLONG read ( char * data, Q_LONGLONG maxlen )
- QByteArray read ( Q_LONGLONG maxlen )
- QByteArray readAll ()
- Q_LONGLONG readLine ( char * data, Q_LONGLONG maxlen )
- QByteArray readLine ( Q_LONGLONG maxlen = 0 )
- virtual bool reset ()
- virtual bool seek ( Q_LONGLONG pos )
- virtual Q_LONGLONG size () const
- void ungetChar ( char c )
- virtual bool waitForBytesWritten ( int msecs )
- virtual bool waitForReadyRead ( int msecs )
- Q_LONGLONG write ( const char * data, Q_LONGLONG maxlen )
- Q_LONGLONG write ( const QByteArray & byteArray )

- 26 public functions inherited from QObject

### Public Slots

- 1 public slot inherited from QObject

### Signals

- void bytesWritten ( Q_LONGLONG bytes )
- void readyRead ()

- 1 signal inherited from QObject

### Static Public Members

- 4 static public members inherited from QObject

### Protected Functions

- virtual Q_LONGLONG readData ( char * data, Q_LONGLONG maxlen ) = 0
- void setErrorString ( const QString & str )
- void setOpenMode ( OpenMode openMode )
- virtual Q_LONGLONG writeData ( const char * data, Q_LONGLONG maxlen ) = 0

- 7 protected functions inherited from QObject

## Detailed Description

The QIODevice class is the base interface class of all I/O devices in Qt.

QIODevice provides both a common implementation and an abstract interface for devices that support reading and writing of blocks of data, such as QFile, QBuffer and QTcpSocket. QIODevice is abstract and can not be instantiated, but is it common to use the interface it defines to provide device-independent I/O features. For example, Qt's XML classes operate on a QIODevice pointer, allowing them to be used with various devices (such as files and buffers).

Before accessing the device, open() must be called to set the correct OpenMode (such as ReadOnly or ReadWrite). You can then write to the device with write() or putChar(), and read by calling either read(), readLine(), or readAll(). Call close() when you are done with the device.

QIODevice distinguishes between two types of devices: random-access devices and sequential devices.

- Random-access devices support seeking to arbitrary positions using seek(). The current position in the file is available by calling pos(). QFile and QBuffer are examples of random-access devices.
- Sequential devices don't support seeking to arbitrary positions. The data must be read in one pass. Functions like pos(), seek(), and size() don't work for sequential devices. QTcpSocket and QProcess are examples of sequential devices.

You can use isSequential() to determine the type of device.

QIODevice emits readyRead() when new data is available for reading; for example, if new data has arrived on the network or if additional data is appended to a file that you are reading from. You can call bytesAvailable() to determine the number of bytes that currently available for reading. It's common to use bytesAvailable() together with the readyRead() signal when programming with asynchronous devices such as QTcpSocket, where fragments of data can arrive at arbitrary points in time. QIODevice emits the bytesWritten() signal every time a payload of data has been written to the device. Use bytesToWrite() to determine the current amount of data waiting to be written.

Certain subclasses of QIODevice, such as QTcpSocket and QProcess, are asynchronous. This means that I/O functions such as write() or read() always return immediately, while communication with the device itself may happen when control goes back to the event loop. QIODevice provides functions that allow you to force these operations to be performed immediately, while blocking the calling thread and without entering the event loop. This allows QIODevice subclasses to be used without an event loop, or in a separate thread:

- flush() - This function suspends operation in the calling thread until all outgoing buffered data has been written to the device.
- waitForReadyRead() - This function suspends operation in the calling thread until new data is available for reading.
- waitForBytesWritten() - This function suspends operation in the calling thread until one payload of data has been written to the device.
- waitFor....() - Subclasses of QIODevice implement blocking functions for device-specific operations. For example, QProcess has a function called waitForStarted() which suspends operation in the calling thread until the process has started.

Calling these functions from the main, GUI thread, may cause your user interface to freeze. Example:

        QProcess gzip;
        gzip.start("gzip", QStringList() << "-c");
        if (!gzip.waitForStarted())
            return false;

        gzip.write("uncompressed data");
        gzip.flush();

        QByteArray compressed;
        while (gzip.waitForReadyRead())
            compressed += gzip.readAll();

By subclassing QIODevice, you can provide the same interface to your own I/O devices. Subclasses of QIODevice are only required to implement the protected readData() and writeData() functions. QIODevice uses these functions to implement all its convenience functions, such as getChar(), readLine() and write(). QIODevice also handles access control for you, so you can safely assume that the device is opened in write mode if writeData() is called.

Some subclasses, such as QFile and QTcpSocket, are implemented using a memory buffer for intermediate storing of data. This reduces the number of required device accessing calls, which are often very slow. Buffering makes functions like getChar() and putChar() fast, as they can operate on the memory buffer instead of directly on the device itself. Certain I/O operations, however, don't work well with a buffer. For example, if several users open the same device and read it character by character, they may end up reading the same data when they meant to read a separate chunk each. For this reason, QIODevice allows you to bypass any buffering by passing the Unbuffered flag to open(). When subclassing QIODevice, remember to bypass any buffer you may use when the device is open in Unbuffered mode.

See also QBuffer, QFile, and QTcpSocket.

## Member Type Documentation

### enum QIODevice::OpenModeFlag
typedef QIODevice::OpenMode

This enum is used with open() to describe the mode in which a device is opened. It is also returned by openMode().

`QIODevice::NotOpen` | The device is not open.
`QIODevice::ReadOnly` | The device is open for reading.
`QIODevice::WriteOnly` | The device is open for writing.
`QIODevice::ReadWrite` | The device is open for reading and writing.
`QIODevice::Append` | The device is opened in append mode, so that all data is written to the end of the file.
`QIODevice::Truncate` | If possible, the device is truncated before it is opened. All earlier contents of the device are lost.
`QIODevice::Translate` | When reading lines using readLine(), end-of-line terminators are translated to the local encoding.
`QIODevice::Unbuffered` | Any buffer in the device is bypassed.

The OpenMode typedef can store a combination of OpenModeFlag values.

## Member Function Documentation

### QIODevice::QIODevice ()

Constructs a QIODevice object.

### QIODevice::QIODevice ( QObject * parent )

Constructs a QIODevice object with the given parent.

### QIODevice::~QIODevice () `[virtual]`

Destructs the QIODevice object.

### bool QIODevice::atEnd () const `[virtual]`

Returns true if the current read and write position is at the end of the device (i.e. there is no more data available for reading on the device); otherwise returns false.

### Q_LONGLONG QIODevice::bytesAvailable () const `[virtual]`

Returns the number of bytes that are available for reading. This function is commonly used with sequential devices to determine the number of bytes to allocate in a buffer before reading.

### Q_LONGLONG QIODevice::bytesToWrite () const `[virtual]`

For buffered devices, this function returns the number of bytes waiting to be written. For devices with no buffer, this function returns 0.

See also flush().

### void QIODevice::bytesWritten ( Q_LONGLONG bytes ) `[signal]`

This signal is emitted every time a payload of data has been written to the device. The bytes argument is set to the number of bytes that were written in this payload.

See also readyRead().

### bool QIODevice::canReadLine () const `[virtual]`

Returns true if a complete line of data can be read from the device; otherwise returns false.

Note that unbuffered devices, which have no way of determining what can be read, always return false.

This function is often called in conjunction with the readyRead() signal.

See also readyRead() and readLine().

### void QIODevice::close () `[virtual]`

Closes the device and sets its OpenMode to NotOpen. The error string is also reset.

See also setOpenMode() and OpenMode.

### QString QIODevice::errorString () const

Returns a human-readable description of the last device error that occurred.

### bool QIODevice::flush () `[virtual]`

This function flushes any pending written data to the device. Returns true on success; otherwise returns false.

If this function returns true, all data is guaranteed to have been written to the device. If it returns false, the number of bytes that have been written can be checked by calling bytesToWrite() before and after the call, or by connecting to bytesWritten().

### bool QIODevice::getChar ( char * c )

Reads one character from the device and stores it in c. If c is 0, the character is discarded. Returns true on success; otherwise returns false.

See also read(), putChar(), and ungetChar().

### bool QIODevice::isOpen () const

Returns true is the device is open; otherwise returns false. A device is open if it can be read from and/or written to. By default, this function returns false if openMode() returns NotOpen.

See also openMode() and OpenMode.

### bool QIODevice::isReadable () const

Returns true if data can be read from the device; otherwise returns false. Use bytesAvailable() to determine how many bytes can be read.

This is a convenience function which checks if the OpenMode of the device contains the ReadOnly flag.

See also openMode() and OpenMode.

### bool QIODevice::isSequential () const `[virtual]`

Returns true if this device is sequential; otherwise returns false.

Sequential devices, as opposed to a random-access devices, have no concept of a start, an end, a size, or a current position, and they do not support seeking. You can only read from the device when it reports that data is available. The most common example of a sequential device is a network socket. On Unix, special files such as /dev/zero and fifo pipes are sequential.

Regular files, on the other hand, do support random access. They have both a size and a current position, and they also support seeking backwards and forwards in the data stream. Regular files are non-sequential.

See also bytesAvailable().

### bool QIODevice::isWritable () const

Returns true if data can be written to the device; otherwise returns false.

This is a convenience function which checks if the OpenMode of the device contains the WriteOnly flag.

See also openMode() and OpenMode.

### bool QIODevice::open ( OpenMode mode ) `[virtual]`

Opens the device and sets its OpenMode to mode.

See also openMode() and OpenMode.

### OpenMode QIODevice::openMode () const

Returns the mode in which the device has been opened; i.e. ReadOnly or WriteOnly.

See also OpenMode.

### Q_LONGLONG QIODevice::pos () const `[virtual]`

For random-access devices, this function returns the position that data is written to or read from. For sequential devices, which have no concept of a current position, 0 is returned.

See also isSequential() and seek().

### bool QIODevice::putChar ( char c )

Writes the character c to the device. Returns true on success; otherwise returns false.

See also write(), getChar(), and ungetChar().

### Q_LONGLONG QIODevice::read ( char * data, Q_LONGLONG maxlen )

Reads at most maxlen bytes from the device into data, and returns the number of bytes read. If an error occurs, such as when attempting to read from a device opened in WriteOnly mode, this function returns -1.

0 is returned when no more data is available for reading.

See also readData(), readLine(), and write().

### QByteArray QIODevice::read ( Q_LONGLONG maxlen )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Reads at most maxlen bytes from the device, and returns the data read as a QByteArray.

This function has no way of reporting errors; returning an empty QByteArray() can mean either that no data was currently available for reading, or that an error occurred.

### QByteArray QIODevice::readAll ()

Reads all available data from the device, and returns it as a QByteArray.

This function has no way of reporting errors; returning an empty QByteArray() can mean either that no data was currently available for reading, or that an error occurred.

### Q_LONGLONG QIODevice::readData ( char * data, Q_LONGLONG maxlen ) `[pure virtual protected]`

Reads up to maxlen bytes from the device into data, and returns the number of bytes read or -1 if an error occurred.

This function is called by QIODevice. Reimplement this function when creating a subclass of QIODevice.

See also read(), readLine(), and writeData().

### Q_LONGLONG QIODevice::readLine ( char * data, Q_LONGLONG maxlen )

This function reads a line of ASCII characters from the device, up to a maximum of maxlen bytes, stores the characters in data, and returns the number of bytes read. If an error occurred, -1 is returned.

If there is room in the buffer (i.e. the line read is shorter than maxlen characters), a '\0' byte is appended to data.

Data is read until either of the following conditions are met:

- The first '\n' character is read.
- maxlen bytes are read.
- The end of the device data is detected.

For example, the following code reads a line of characters from a file:

        QFile file("box.txt");
        if (file.open(QFile::ReadOnly)) {
            char buf[1024];
            Q_LONGLONG lineLength = file.readLine(buf, sizeof(buf));
            if (lineLength != -1) {
                // the line is available in buf
            }
        }

If the '\n' character is the 1024th character read then it will be inserted into the buffer; if it occurs after the 1024 character then it is not read.

See also getChar(), read(), and write().

### QByteArray QIODevice::readLine ( Q_LONGLONG maxlen = 0 )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Reads a line from the device, but no more than maxlen characters, and returns the result as a QByteArray.

This function has no way of reporting errors; returning an empty QByteArray() can mean either that no data was currently available for reading, or that an error occurred.

### void QIODevice::readyRead () `[signal]`

This signal is emitted every time new data is available for reading from the device.

See also bytesWritten().

### bool QIODevice::reset () `[virtual]`

Seeks to the start of input for random-access devices. Returns true on success; otherwise returns false (for example, if the device is not open).

See also seek().

### bool QIODevice::seek ( Q_LONGLONG pos ) `[virtual]`

For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred. For sequential devices, the default behavior is to do nothing and return false.

See also pos().

### void QIODevice::setErrorString ( const QString & str ) `[protected]`

Sets the human readable description of the last device error that occurred to str.

### void QIODevice::setOpenMode ( OpenMode openMode ) `[protected]`

Sets the OpenMode of the device to openMode. Reimplement this function to set the open mode when reimplementing open().

See also openMode() and OpenMode.

### Q_LONGLONG QIODevice::size () const `[virtual]`

For random-access devices, this function returns the size of the device. For sequential devices, bytesAvailable() is returned.

### void QIODevice::ungetChar ( char c )

Puts the character c back into the device, and decrements the current position unless the position is 0. This function is usually called to "undo" a getChar() operation, such as when writing a backtracking parser.

### bool QIODevice::waitForBytesWritten ( int msecs ) `[virtual]`

For buffered devices, this function waits until a payload of buffered written data has been written to the device and the bytesWritten() signal has been emitted, or until msecs milliseconds have passed. For unbuffered devices, it does nothing.

Returns true if a payload of data was written to the device; otherwise returns false (i.e. if the operation timed out, or if an error occurred).

This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.

Warning: Calling this function from the main (GUI) thread might cause your user interface to freeze.

See also waitForReadyRead().

### bool QIODevice::waitForReadyRead ( int msecs ) `[virtual]`

Blocks until data is available for reading and the readyRead() signal has been emitted, or until msecs milliseconds have passed.

Returns true if data is available for reading; otherwise returns false (if the operation timed out or if an error occurred).

This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.

Warning: Calling this function from the main (GUI) thread might cause your user interface to freeze.

See also waitForBytesWritten().

### Q_LONGLONG QIODevice::write ( const char * data, Q_LONGLONG maxlen )

Writes at most maxlen bytes of data from data to the device. Returns the number of bytes that were actually written, or -1 if an error occurred.

See also read() and writeData().

### Q_LONGLONG QIODevice::write ( const QByteArray & byteArray )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Writes the content of byteArray to the device. Returns the number of bytes that were actually written, or -1 if an error occurred.

See also read() and writeData().

### Q_LONGLONG QIODevice::writeData ( const char * data, Q_LONGLONG maxlen ) `[pure virtual protected]`

Writes up to maxlen bytes from data to the device. Returns the number of bytes written, or -1 if an error occurred.

This function is called by QIODevice. Reimplement this function when creating a subclass of QIODevice.

See also read() and write().