Qt 4.8
Public Types | Signals | Public Functions | Protected Functions | List of all members
QIODevice Class Referenceabstract

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

#include <qiodevice.h>

Inheritance diagram for QIODevice:
QObject InputPrivate InputPrivate MacOutputDevice OutputPrivate OutputPrivate QAbstractSocket QAuthDevice QBuffer QByteDeviceWrappingIoDevice QFile QHttpMultiPartIODevice QLocalSocket QNetworkReply QOstDevice QProcess QtMultimediaInternal::MacInputDevice QUnixSocket

Public Types

enum  OpenModeFlag {
  NotOpen = 0x0000, ReadOnly = 0x0001, WriteOnly = 0x0002, ReadWrite = ReadOnly | WriteOnly,
  Append = 0x0004, Truncate = 0x0008, Text = 0x0010, Unbuffered = 0x0020
}
 This enum is used with open() to describe the mode in which a device is opened. More...
 

Signals

void aboutToClose ()
 This signal is emitted when the device is about to close. More...
 
void bytesWritten (qint64 bytes)
 This signal is emitted every time a payload of data has been written to the device. More...
 
void readChannelFinished ()
 This signal is emitted when the input (reading) stream is closed in this device. More...
 
void readyRead ()
 This signal is emitted once every time new data is available for reading from the device. More...
 
- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 

Public Functions

virtual bool atEnd () const
 Returns true if the current read and write position is at the end of the device (i.e. More...
 
virtual qint64 bytesAvailable () const
 Returns the number of bytes that are available for reading. More...
 
virtual qint64 bytesToWrite () const
 For buffered devices, this function returns the number of bytes waiting to be written. More...
 
virtual bool canReadLine () const
 Returns true if a complete line of data can be read from the device; otherwise returns false. More...
 
virtual void close ()
 First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen. More...
 
QString errorString () const
 Returns a human-readable description of the last device error that occurred. More...
 
bool getChar (char *c)
 Reads one character from the device and stores it in c. More...
 
bool isOpen () const
 Returns true if the device is open; otherwise returns false. More...
 
bool isReadable () const
 Returns true if data can be read from the device; otherwise returns false. More...
 
virtual bool isSequential () const
 Returns true if this device is sequential; otherwise returns false. More...
 
bool isTextModeEnabled () const
 Returns true if the Text flag is enabled; otherwise returns false. More...
 
bool isWritable () const
 Returns true if data can be written to the device; otherwise returns false. More...
 
virtual bool open (OpenMode mode)
 Opens the device and sets its OpenMode to mode. More...
 
OpenMode openMode () const
 Returns the mode in which the device has been opened; i.e. More...
 
qint64 peek (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, without side effects (i. More...
 
QByteArray peek (qint64 maxlen)
 Peeks at most maxSize bytes from the device, returning the data peeked as a QByteArray. More...
 
virtual qint64 pos () const
 For random-access devices, this function returns the position that data is written to or read from. More...
 
bool putChar (char c)
 Writes the character c to the device. More...
 
 QIODevice ()
 Constructs a QIODevice object. More...
 
 QIODevice (QObject *parent)
 Constructs a QIODevice object with the given parent. More...
 
qint64 read (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, and returns the number of bytes read. More...
 
QByteArray read (qint64 maxlen)
 Reads at most maxSize bytes from the device, and returns the data read as a QByteArray. More...
 
QByteArray readAll ()
 Reads all available data from the device, and returns it as a QByteArray. More...
 
qint64 readLine (char *data, qint64 maxlen)
 This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes, stores the characters in data, and returns the number of bytes read. More...
 
QByteArray readLine (qint64 maxlen=0)
 Reads a line from the device, but no more than maxSize characters, and returns the result as a QByteArray. More...
 
virtual bool reset ()
 Seeks to the start of input for random-access devices. More...
 
virtual bool seek (qint64 pos)
 For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred. More...
 
void setTextModeEnabled (bool enabled)
 If enabled is true, this function sets the Text flag on the device; otherwise the Text flag is removed. More...
 
virtual qint64 size () const
 For open random-access devices, this function returns the size of the device. More...
 
void ungetChar (char c)
 Puts the character c back into the device, and decrements the current position unless the position is 0. More...
 
virtual bool waitForBytesWritten (int msecs)
 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. More...
 
virtual bool waitForReadyRead (int msecs)
 Blocks until new data is available for reading and the readyRead() signal has been emitted, or until msecs milliseconds have passed. More...
 
qint64 write (const char *data, qint64 len)
 Writes at most maxSize bytes of data from data to the device. More...
 
qint64 write (const char *data)
 Writes data from a zero-terminated string of 8-bit characters to the device. More...
 
qint64 write (const QByteArray &data)
 Writes the content of byteArray to the device. More...
 
virtual ~QIODevice ()
 The destructor is virtual, and QIODevice is an abstract base class. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Protected Functions

 QIODevice (QIODevicePrivate &dd, QObject *parent=0)
 
virtual qint64 readData (char *data, qint64 maxlen)=0
 Reads up to maxSize bytes from the device into data, and returns the number of bytes read or -1 if an error occurred. More...
 
virtual qint64 readLineData (char *data, qint64 maxlen)
 Reads up to maxSize characters into data and returns the number of characters read. More...
 
void setErrorString (const QString &errorString)
 Sets the human readable description of the last device error that occurred to str. More...
 
void setOpenMode (OpenMode openMode)
 Sets the OpenMode of the device to openMode. More...
 
virtual qint64 writeData (const char *data, qint64 len)=0
 Writes up to maxSize bytes from data to the device. More...
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Additional Inherited Members

- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 
- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 
- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

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

Note
This class or function is reentrant.

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 it is 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.

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 are 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:

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");
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 QTcpSocket

Definition at line 66 of file qiodevice.h.

Enumerations

◆ OpenModeFlag

This enum is used with open() to describe the mode in which a device is opened.

It is also returned by openMode().

  • NotOpen The device is not open.
  • ReadOnly The device is open for reading.
  • WriteOnly The device is open for writing.
  • ReadWrite The device is open for reading and writing.
  • Append The device is opened in append mode, so that all data is written to the end of the file.
  • Truncate If possible, the device is truncated before it is opened. All earlier contents of the device are lost.
  • Text When reading, the end-of-line terminators are translated to '
    '. When writing, the end-of-line terminators are translated to the local encoding, for example '
    ' for Win32.
  • Unbuffered Any buffer in the device is bypassed.

Certain flags, such as Unbuffered and Truncate, are meaningless when used with some subclasses. Some of these restrictions are implied by the type of device that is represented by a subclass. In other cases, the restriction may be due to the implementation, or may be imposed by the underlying platform; for example, QTcpSocket does not support Unbuffered mode, and limitations in the native API prevent QFile from supporting Unbuffered on Windows.

Enumerator
NotOpen 
ReadOnly 
WriteOnly 
ReadWrite 
Append 
Truncate 
Text 
Unbuffered 

Definition at line 75 of file qiodevice.h.

75  {
76  NotOpen = 0x0000,
77  ReadOnly = 0x0001,
78  WriteOnly = 0x0002,
80  Append = 0x0004,
81  Truncate = 0x0008,
82  Text = 0x0010,
83  Unbuffered = 0x0020
84  };
The Text item allows you to add formatted text to a scene.

Constructors and Destructors

◆ QIODevice() [1/3]

QIODevice::QIODevice ( )

Constructs a QIODevice object.

Definition at line 390 of file qiodevice.cpp.

Referenced by QIODevicePrivate::~QIODevicePrivate().

391  : QObject(*new QIODevicePrivate, 0)
392 {
393 #if defined QIODEVICE_DEBUG
394  QFile *file = qobject_cast<QFile *>(this);
395  printf("%p QIODevice::QIODevice(\"%s\") %s\n", this, metaObject()->className(),
396  qPrintable(file ? file->fileName() : QString()));
397 #endif
398 }
QString fileName() const
Returns the name set by setFileName() or to the QFile constructors.
Definition: qfile.cpp:470
The QString class provides a Unicode character string.
Definition: qstring.h:83
T * qobject_cast(QObject *object)
Definition: qobject.h:375
const char * className
Definition: qwizard.cpp:137
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753
#define qPrintable(string)
Definition: qglobal.h:1750
virtual const QMetaObject * metaObject() const
Returns a pointer to the meta-object of this object.

◆ QIODevice() [2/3]

QIODevice::QIODevice ( QObject parent)
explicit

Constructs a QIODevice object with the given parent.

Definition at line 404 of file qiodevice.cpp.

405  : QObject(*new QIODevicePrivate, parent)
406 {
407 #if defined QIODEVICE_DEBUG
408  printf("%p QIODevice::QIODevice(%p \"%s\")\n", this, parent, metaObject()->className());
409 #endif
410 }
const char * className
Definition: qwizard.cpp:137
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753
virtual const QMetaObject * metaObject() const
Returns a pointer to the meta-object of this object.

◆ ~QIODevice()

QIODevice::~QIODevice ( )
virtual

The destructor is virtual, and QIODevice is an abstract base class.

This destructor does not call close(), but the subclass destructor might. If you are in doubt, call close() before destroying the QIODevice.

Definition at line 427 of file qiodevice.cpp.

428 {
429 #if defined QIODEVICE_DEBUG
430  printf("%p QIODevice::~QIODevice()\n", this);
431 #endif
432 }

◆ QIODevice() [3/3]

QIODevice::QIODevice ( QIODevicePrivate dd,
QObject parent = 0 
)
protected
Warning
This function is not part of the public interface.

Definition at line 414 of file qiodevice.cpp.

415  : QObject(dd, parent)
416 {
417 }
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753

Functions

◆ aboutToClose

QIODevice::aboutToClose ( )
signal

This signal is emitted when the device is about to close.

Connect this signal if you have operations that need to be performed before the device closes (e.g., if you have data in a separate buffer that needs to be written to the device).

Referenced by close(), QProcess::close(), and QPatternist::QIODeviceDelegate::QIODeviceDelegate().

◆ atEnd()

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.

For some devices, atEnd() can return true even though there is more data to read. This special case only applies to devices that generate data in direct response to you calling read() (e.g., /dev or /proc files on Unix and Mac OS X, or console input / stdin on all platforms).

See also
bytesAvailable(), read(), isSequential()

Reimplemented in QAuthDevice, QProcess, QByteDeviceWrappingIoDevice, QAbstractSocket, QFile, QHttpMultiPartIODevice, QSslSocket, QBuffer, and QPatternist::QIODeviceDelegate.

Definition at line 711 of file qiodevice.cpp.

Referenced by QNetworkReplyImplPrivate::_q_copyReadyRead(), QPatternist::QIODeviceDelegate::atEnd(), QBuffer::atEnd(), QSslSocket::atEnd(), QDataStream::atEnd(), QAbstractSocket::atEnd(), QProcess::atEnd(), QPSPrintEnginePrivate::emitPages(), QPdf::ByteStream::operator<<(), QHttpPrivate::postMoreData(), QPdf::ByteStream::prepareBuffer(), qt_read_dibv5(), read_dib_body(), QNonContiguousByteDeviceIoDeviceImpl::readPointer(), QTextStreamPrivate::scan(), QFile::symLinkTarget(), QNetworkDiskCache::updateMetaData(), and QPdfEnginePrivate::writeCompressed().

712 {
713  Q_D(const QIODevice);
714 #if defined QIODEVICE_DEBUG
715  printf("%p QIODevice::atEnd() returns %s, d->openMode == %d, d->pos == %d\n", this, (d->openMode == NotOpen || d->pos == size()) ? "true" : "false",
716  int(d->openMode), int(d->pos));
717 #endif
718  return d->openMode == NotOpen || (d->buffer.isEmpty() && bytesAvailable() == 0);
719 }
double d
Definition: qnumeric_p.h:62
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
#define Q_D(Class)
Definition: qglobal.h:2482
virtual qint64 bytesAvailable() const
Returns the number of bytes that are available for reading.
Definition: qiodevice.cpp:752
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66

◆ bytesAvailable()

qint64 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.

Subclasses that reimplement this function must call the base implementation in order to include the size of QIODevices' buffer. Example:

qint64 CustomDevice::bytesAvailable() const
{
return buffer.size() + QIODevice::bytesAvailable();
}
See also
bytesToWrite(), readyRead(), isSequential()

Reimplemented in QAuthDevice, QProcess, QUnixSocket, QAbstractSocket, QHttpMultiPartIODevice, QSslSocket, QLocalSocket, QNetworkReplyImpl, QNetworkReplyFileImpl, QNetworkReplyDataImpl, QPatternist::QIODeviceDelegate, and QOstDevice.

Definition at line 752 of file qiodevice.cpp.

Referenced by QNetworkReplyImplPrivate::_q_bufferOutgoingData(), QNetworkReplyImplPrivate::_q_copyReadyRead(), QLocalSocketPrivate::_q_pipeClosed(), atEnd(), QFile::atEnd(), QPatternist::QIODeviceDelegate::bytesAvailable(), QNetworkReplyDataImpl::bytesAvailable(), QNetworkReplyFileImpl::bytesAvailable(), QNetworkReplyImpl::bytesAvailable(), QLocalSocket::bytesAvailable(), QSslSocket::bytesAvailable(), QAbstractSocket::bytesAvailable(), QUnixSocket::bytesAvailable(), QProcess::bytesAvailable(), qws_read_command(), qws_read_uint(), QWSClient::readMoreCommand(), QPacketProtocolPrivate::readyToRead(), QAuthDevice::recvReadyRead(), and size().

753 {
754  Q_D(const QIODevice);
755  if (!d->isSequential())
756  return qMax(size() - d->pos, qint64(0));
757  return d->buffer.size();
758 }
double d
Definition: qnumeric_p.h:62
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
#define Q_D(Class)
Definition: qglobal.h:2482
Q_DECL_CONSTEXPR const T & qMax(const T &a, const T &b)
Definition: qglobal.h:1217
__int64 qint64
Definition: qglobal.h:942
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66

◆ bytesToWrite()

qint64 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
bytesAvailable(), bytesWritten(), isSequential()

Reimplemented in QAuthDevice, QProcess, QUnixSocket, QHttpMultiPartIODevice, QAbstractSocket, QSslSocket, QLocalSocket, and QPatternist::QIODeviceDelegate.

Definition at line 767 of file qiodevice.cpp.

Referenced by QPatternist::QIODeviceDelegate::bytesToWrite().

768 {
769  return qint64(0);
770 }
__int64 qint64
Definition: qglobal.h:942

◆ bytesWritten

QIODevice::bytesWritten ( qint64  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.

bytesWritten() is not emitted recursively; if you reenter the event loop or call waitForBytesWritten() inside a slot connected to the bytesWritten() signal, the signal will not be reemitted (although waitForBytesWritten() may still return true).

See also
readyRead()

Referenced by QAuthDevice::QAuthDevice(), QPatternist::QIODeviceDelegate::QIODeviceDelegate(), QAuthDevice::targetBytesWritten(), QUnixSocket::waitForBytesWritten(), QUnixSocketPrivate::writeActivated(), QOstDevice::writeData(), QAbstractSocket::writeData(), and QUdpSocket::writeDatagram().

◆ canReadLine()

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.

Subclasses that reimplement this function must call the base implementation in order to include the contents of the QIODevice's buffer. Example:

bool CustomDevice::canReadLine() const
{
return buffer.contains('\n') || QIODevice::canReadLine();
}
See also
readyRead(), readLine()

Reimplemented in QProcess, QUnixSocket, QAbstractSocket, QSslSocket, QLocalSocket, QBuffer, QNetworkReplyImpl, and QPatternist::QIODeviceDelegate.

Definition at line 1330 of file qiodevice.cpp.

Referenced by QLocalSocketPrivate::_q_pipeClosed(), QPatternist::QIODeviceDelegate::canReadLine(), QNetworkReplyImpl::canReadLine(), QBuffer::canReadLine(), QLocalSocket::canReadLine(), QSslSocket::canReadLine(), QAbstractSocket::canReadLine(), and QProcess::canReadLine().

1331 {
1332  return d_func()->buffer.canReadLine();
1333 }

◆ close()

void QIODevice::close ( )
virtual

First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen.

The error string is also reset.

See also
setOpenMode() OpenMode

Reimplemented in QProcess, QAbstractSocket, QFile, QUnixSocket, QHttpMultiPartIODevice, QSslSocket, QNetworkReply, QLocalSocket, QBuffer, QNetworkReplyImpl, QPatternist::QIODeviceDelegate, QNetworkReplyFileImpl, QNetworkReplyDataImpl, and QOstDevice.

Definition at line 590 of file qiodevice.cpp.

Referenced by QLocalSocketPrivate::_q_pipeClosed(), QZipWriter::addFile(), QOstDevice::close(), QPatternist::QIODeviceDelegate::close(), QBuffer::close(), QLocalSocket::close(), QZipWriter::close(), QNetworkReply::close(), QZipReader::close(), QHttpMultiPartIODevice::close(), QFile::close(), QAbstractSocket::close(), QProcess::close(), QNetworkAccessCacheBackend::closeDownstreamChannel(), QPdfBaseEnginePrivate::closePrintDevice(), QAbstractSocket::disconnectFromHostImplementation(), qws_read_command(), QFile::symLinkTarget(), QTextDocumentWriter::write(), and QXmlStreamStrategy::~QXmlStreamStrategy().

591 {
592  Q_D(QIODevice);
593  if (d->openMode == NotOpen)
594  return;
595 
596 #if defined QIODEVICE_DEBUG
597  printf("%p QIODevice::close()\n", this);
598 #endif
599 
600 #ifndef QT_NO_QOBJECT
601  emit aboutToClose();
602 #endif
603  d->openMode = NotOpen;
604  d->errorString.clear();
605  d->pos = 0;
606  d->seqDumpPos = 0;
607  d->buffer.clear();
608  d->firstRead = true;
609 }
double d
Definition: qnumeric_p.h:62
void aboutToClose()
This signal is emitted when the device is about to close.
#define Q_D(Class)
Definition: qglobal.h:2482
#define emit
Definition: qobjectdefs.h:76
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66

◆ errorString()

QString QIODevice::errorString ( ) const

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

See also
setErrorString()

Definition at line 1671 of file qiodevice.cpp.

Referenced by QHttpNetworkConnectionChannel::_q_error(), QSslSocketPrivate::_q_errorSlot(), QHttpPrivate::_q_slotError(), QSocks5SocketEngine::bind(), QSvgTinyDocument::load(), QPatternist::AccelTreeResourceLoader::load(), QDeclarativePixmapReader::networkRequestDone(), QNetworkAccessFileBackend::open(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), qt_parse_pattern(), QNetworkAccessFileBackend::readMoreFromFile(), QFile::rename(), QSocks5SocketEnginePrivate::setErrorState(), QSslSocketBackendPrivate::transmit(), QNetworkAccessFileBackend::uploadReadyReadSlot(), QAbstractSocket::waitForBytesWritten(), QAbstractSocket::waitForDisconnected(), and QAbstractSocket::waitForReadyRead().

1672 {
1673  Q_D(const QIODevice);
1674  if (d->errorString.isEmpty()) {
1675 #ifdef QT_NO_QOBJECT
1676  return QLatin1String(QT_TRANSLATE_NOOP(QIODevice, "Unknown error"));
1677 #else
1678  return tr("Unknown error");
1679 #endif
1680  }
1681  return d->errorString;
1682 }
double d
Definition: qnumeric_p.h:62
#define QT_TRANSLATE_NOOP(scope, x)
Marks the string literal sourceText for dynamic translation in the given context; i...
Definition: qglobal.h:2487
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
#define Q_D(Class)
Definition: qglobal.h:2482
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66

◆ getChar()

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() ungetChar()

Definition at line 1536 of file qiodevice.cpp.

Referenced by QNonContiguousByteDeviceIoDeviceImpl::advanceReadPointer(), Tga16Reader::operator()(), Tga24Reader::operator()(), Tga32Reader::operator()(), QDataStream::operator>>(), read_dib_body(), read_pbm_int(), read_xpm_body(), QTgaFile::readImage(), and runningUnderDebugger().

1537 {
1538  // readability checked in read()
1539  char ch;
1540  return (1 == read(c ? c : &ch, 1));
1541 }
unsigned char c[8]
Definition: qnumeric_p.h:62
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read...
Definition: qiodevice.cpp:791

◆ isOpen()

bool QIODevice::isOpen ( ) const

Returns true if 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() OpenMode

Definition at line 530 of file qiodevice.cpp.

Referenced by QNetworkReplyImplPrivate::_q_copyReadyRead(), QFtpPrivate::_q_startNextCommand(), QZipWriterPrivate::addEntry(), QFile::atEnd(), QAbstractSocket::atEnd(), QProcess::atEnd(), QBuffer::canReadLine(), QImageWriter::canWrite(), QTiffPlugin::capabilities(), QICOPlugin::capabilities(), QJpegPlugin::capabilities(), QTgaPlugin::capabilities(), QMngPlugin::capabilities(), QPicturePrivate::checkFormat(), QFile::close(), QHttpPrivate::closeConn(), QTemporaryFile::createLocalFile(), QUuid::createUuid(), errorString(), QXmlInputSource::fetchData(), QTransportAuthPrivate::getClientKey(), QFile::handle(), QNetworkReplyImplPrivate::initCacheSaveDevice(), QImageReaderPrivate::initHandler(), QAbstractSocket::isValid(), QOstDevice::open(), QFile::open(), QPatternist::XsdStateMachine< XsdSchemaToken::NodeName >::outputGraph(), QNetworkAccessManagerPrivate::prepareMultipart(), QPicturePrivate::QPicturePrivate(), qt_inflateGZipDataFrom(), QXmlInputSource::QXmlInputSource(), QPictureIO::read(), QFile::rename(), QFile::resize(), QZipReaderPrivate::scanFiles(), QFile::seek(), QBuffer::setBuffer(), QBuffer::setData(), QFile::setFileName(), setTextModeEnabled(), QNetworkDiskCachePrivate::storeItem(), QConfFileSettingsPrivate::syncConfFile(), and QPictureIO::write().

531 {
532  return d_func()->openMode != NotOpen;
533 }

◆ isReadable()

bool QIODevice::isReadable ( ) const

◆ isSequential()

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.

The QIODevice implementation returns false.

See also
bytesAvailable()

Reimplemented in QtMultimediaInternal::MacInputDevice, MacOutputDevice, QAuthDevice, QProcess, QUnixSocket, QByteDeviceWrappingIoDevice, QAbstractSocket, QFile, QHttpMultiPartIODevice, QNetworkReply, QLocalSocket, QPatternist::QIODeviceDelegate, QNetworkReplyFileImpl, and QNetworkReplyDataImpl.

Definition at line 454 of file qiodevice.cpp.

Referenced by QNetworkReplyImplPrivate::_q_copyReadyRead(), QFtpPrivate::_q_startNextCommand(), QXbmHandler::canRead(), ICOReader::canRead(), createReadHandlerHelper(), QNetworkAccessManager::createRequest(), QTextStreamPrivate::fillReadBuffer(), QMoviePrivate::infoForFrame(), iod_read_fn(), QPatternist::QIODeviceDelegate::isSequential(), QHttpMultiPartIODevice::isSequential(), QPdf::ByteStream::operator<<(), QtIcoHandler::option(), QPdf::ByteStream::prepareBuffer(), QFtp::put(), QPatternist::QIODeviceDelegate::QIODeviceDelegate(), qt_term_source(), QTgaFile::QTgaFile(), QUnixSocket::read(), read_dib_body(), readLineData(), QNonContiguousByteDeviceIoDeviceImpl::readPointer(), QNetworkReplyImplPrivate::setup(), QNonContiguousByteDeviceIoDeviceImpl::size(), QDataStream::skipRawData(), and QFile::symLinkTarget().

455 {
456  return false;
457 }

◆ isTextModeEnabled()

bool QIODevice::isTextModeEnabled ( ) const

Returns true if the Text flag is enabled; otherwise returns false.

See also
setTextModeEnabled()

Definition at line 517 of file qiodevice.cpp.

Referenced by QTextStreamPrivate::fillReadBuffer(), and QTextStreamPrivate::flushWriteBuffer().

518 {
519  return d_func()->openMode & Text;
520 }

◆ isWritable()

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() OpenMode

Definition at line 558 of file qiodevice.cpp.

Referenced by QImageWriter::canWrite(), QTiffPlugin::capabilities(), QICOPlugin::capabilities(), QJpegPlugin::capabilities(), QXmlQuery::evaluateTo(), QZipWriter::isWritable(), qt_write_dib(), qt_write_dibv5(), QXmlSerializer::QXmlSerializer(), QBuffer::seek(), QConfFileSettingsPrivate::syncConfFile(), QTextDocumentWriter::write(), write_xpm_image(), and QTextOdfWriter::writeAll().

559 {
560  return (openMode() & WriteOnly) != 0;
561 }
OpenMode openMode() const
Returns the mode in which the device has been opened; i.e.
Definition: qiodevice.cpp:465

◆ open()

bool QIODevice::open ( OpenMode  mode)
virtual

Opens the device and sets its OpenMode to mode.

Returns true if successful; otherwise returns false. This function should be called from any reimplementations of open() or other functions that open the device.

See also
openMode() OpenMode

Reimplemented in QFile, QTemporaryFile, QBuffer, and QPatternist::QIODeviceDelegate.

Definition at line 570 of file qiodevice.cpp.

Referenced by QLocalSocketPrivate::_q_pipeClosed(), QFtpPrivate::_q_startNextCommand(), QZipWriterPrivate::addEntry(), QZipWriter::addFile(), QPdf::ByteStream::ByteStream(), QImageWriter::canWrite(), QPdf::ByteStream::clear(), QSslSocket::connectToHostImplementation(), QAbstractSocket::connectToHostImplementation(), QLocalSocket::connectToServer(), QPdf::ByteStream::constructor_helper(), QXmlInputSource::fetchData(), QAudioOutputPrivate::freeBlocks(), QAudioInputPrivate::freeBlocks(), QImageReaderPrivate::initHandler(), QOstDevice::open(), QPatternist::QIODeviceDelegate::open(), QBuffer::open(), QFile::open(), QNetworkAccessManagerPrivate::prepareMultipart(), QAuthDevice::QAuthDevice(), QByteDeviceWrappingIoDevice::QByteDeviceWrappingIoDevice(), QNetworkReplyDataImpl::QNetworkReplyDataImpl(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), qt_inflateGZipDataFrom(), QZipStreamStrategy::QZipStreamStrategy(), QCacheItem::read(), QAuthDevice::recvReadyRead(), QZipReaderPrivate::scanFiles(), QLocalSocket::setSocketDescriptor(), QAbstractSocket::setSocketDescriptor(), QAudioOutputPrivate::start(), QAudioInputPrivate::start(), QProcess::start(), QFile::symLinkTarget(), QTextDocumentWriter::write(), and QTextOdfWriter::writeAll().

571 {
572  Q_D(QIODevice);
573  d->openMode = mode;
574  d->pos = (mode & Append) ? size() : qint64(0);
575  d->buffer.clear();
576  d->accessMode = QIODevicePrivate::Unset;
577  d->firstRead = true;
578 #if defined QIODEVICE_DEBUG
579  printf("%p QIODevice::open(0x%x)\n", this, quint32(mode));
580 #endif
581  return true;
582 }
double d
Definition: qnumeric_p.h:62
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
#define Q_D(Class)
Definition: qglobal.h:2482
__int64 qint64
Definition: qglobal.h:942
unsigned int quint32
Definition: qglobal.h:938
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66

◆ openMode()

QIODevice::OpenMode QIODevice::openMode ( ) const

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

ReadOnly or WriteOnly.

See also
OpenMode

Definition at line 465 of file qiodevice.cpp.

Referenced by QZipWriter::addFile(), QPacket::clear(), QZipWriter::close(), QAbstractSocket::connectToHost(), isReadable(), isWritable(), QPatternist::QIODeviceDelegate::open(), QFilePrivate::putCharHelper(), QPacket::QPacket(), QPicturePrivate::QPicturePrivate(), QZipReaderPrivate::scanFiles(), and setOpenMode().

466 {
467  return d_func()->openMode;
468 }

◆ peek() [1/2]

qint64 QIODevice::peek ( char *  data,
qint64  maxSize 
)

Reads at most maxSize bytes from the device into data, without side effects (i.

Since
4.1

e., if you call read() after peek(), you will get the same data). Returns the number of bytes read. If an error occurs, such as when attempting to peek a device opened in WriteOnly mode, this function returns -1.

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

Example:

bool isExeFile(QFile *file)
{
char buf[2];
if (file->peek(buf, sizeof(buf)) == sizeof(buf))
return (buf[0] == 'M' && buf[1] == 'Z');
return false;
}
See also
read()

Definition at line 1563 of file qiodevice.cpp.

Referenced by QHttpNetworkConnectionChannel::_q_readyRead(), QTiffHandler::canRead(), QSvgIOHandler::canRead(), QJpegHandler::canRead(), QGifHandler::canRead(), QXpmHandler::canRead(), QMngHandler::canRead(), QPpmHandler::canRead(), QPngHandler::canRead(), QBmpHandler::canRead(), QGLPixmapData::fromFile(), QHttpNetworkReplyPrivate::getChunkSize(), QSslSocketPrivate::peek(), and QSslSocketBackendPrivate::transmit().

1564 {
1565  return d_func()->peek(data, maxSize);
1566 }
static const char * data(const QByteArray &arr)

◆ peek() [2/2]

QByteArray QIODevice::peek ( qint64  maxSize)

Peeks at most maxSize bytes from the device, returning the data peeked as a QByteArray.

Since
4.1 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Example:

bool isExeFile(QFile *file)
{
return file->peek(2) == "MZ";
}

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

See also
read()

Definition at line 1588 of file qiodevice.cpp.

1589 {
1590  return d_func()->peek(maxSize);
1591 }

◆ pos()

qint64 QIODevice::pos ( ) const
virtual

For random-access devices, this function returns the position that data is written to or read from.

For sequential devices or closed devices, where there is no concept of a "current position", 0 is returned.

The current read/write position of the device is maintained internally by QIODevice, so reimplementing this function is not necessary. When subclassing QIODevice, use QIODevice::seek() to notify QIODevice about changes in the device position.

See also
isSequential(), seek()

Reimplemented in QFile, QBuffer, and QPatternist::QIODeviceDelegate.

Definition at line 624 of file qiodevice.cpp.

Referenced by QZipWriterPrivate::addEntry(), QTiffHandler::canRead(), QXbmHandler::canRead(), ICOReader::canRead(), QZipWriter::close(), QTextStreamPrivate::consume(), createReadHandlerHelper(), QAudioOutputPrivate::deviceReady(), QPicture::exec(), QZipReader::fileData(), QAudioOutputPrivate::freeBlocks(), iod_read_fn(), QPdf::ByteStream::operator<<(), QTiffHandler::option(), QtIcoHandler::option(), QPictureIO::pictureFormat(), QPatternist::QIODeviceDelegate::pos(), QBuffer::pos(), QFile::pos(), QHttpPrivate::postMoreData(), QPdf::ByteStream::prepareBuffer(), QMovie::QMovie(), QNonContiguousByteDeviceIoDeviceImpl::QNonContiguousByteDeviceIoDeviceImpl(), qt_term_source(), qtiffSeekProc(), read_dib_body(), QBmpHandler::readHeader(), ICOReader::readHeader(), QMoviePrivate::reset(), QTextStreamPrivate::resetReadBuffer(), QGIFFormat::scan(), seek(), QDataStream::skipRawData(), QFile::symLinkTarget(), and ICOReader::write().

625 {
626  Q_D(const QIODevice);
627 #if defined QIODEVICE_DEBUG
628  printf("%p QIODevice::pos() == %d\n", this, int(d->pos));
629 #endif
630  return d->pos;
631 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66

◆ putChar()

bool QIODevice::putChar ( char  c)

Writes the character c to the device.

Returns true on success; otherwise returns false.

See also
write() getChar() ungetChar()

Definition at line 1486 of file qiodevice.cpp.

Referenced by QDataStream::operator<<(), and QXmlSerializerPrivate::write().

1487 {
1488  return d_func()->putCharHelper(c);
1489 }
unsigned char c[8]
Definition: qnumeric_p.h:62

◆ read() [1/2]

qint64 QIODevice::read ( char *  data,
qint64  maxSize 
)

Reads at most maxSize 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. However, reading past the end of the stream is considered an error, so this function returns -1 in those cases (that is, reading on a closed socket or after a process has died).

See also
readData() readLine() write()

Definition at line 791 of file qiodevice.cpp.

Referenced by QNetworkReplyImplPrivate::_q_bufferOutgoingData(), QNetworkReplyImplPrivate::_q_copyReadyRead(), QHttpPrivate::_q_slotReadyRead(), QVNCServer::clientCutText(), QSocks5PasswordAuthenticator::continueAuthenticate(), QFile::copy(), QTemporaryFile::createLocalFile(), QUuid::createUuid(), QAudioOutputPrivate::deviceReady(), QTranslatorPrivate::do_load(), QPSPrintEnginePrivate::emitPages(), QXmlInputSource::fetchData(), QZipReader::fileData(), QtMultimediaInternal::QAudioOutputBuffer::fillBuffer(), QTextStreamPrivate::fillReadBuffer(), QAudioOutputPrivate::freeBlocks(), getChar(), QXmlStreamReaderPrivate::getChar_helper(), QHttpNetworkReplyPrivate::getChunkSize(), QTransportAuthPrivate::getClientKey(), ICOReader::iconAt(), iod_read_fn(), QPdf::ByteStream::operator<<(), QDataStream::operator>>(), QSocks5SocketEnginePrivate::parseAuthenticationMethodReply(), QPictureIO::pictureFormat(), QHttpPrivate::postMoreData(), QPdf::ByteStream::prepareBuffer(), qt_fill_input_buffer(), qt_inflateGZipDataFrom(), qt_read_dibv5(), QTgaFile::QTgaFile(), qtiffReadProc(), qws_read_command(), qws_read_uint(), QFtpDTP::read(), read(), QRfbRect::read(), QRfbPixelFormat::read(), QUnixSocket::read(), QRfbServerInit::read(), QRfbSetEncodings::read(), QRfbFrameBufferUpdateRequest::read(), QRfbKeyEvent::read(), QRfbPointerEvent::read(), QRfbClientCutText::read(), ICOReader::read16_24_32BMP(), ICOReader::read1BitBMP(), ICOReader::read4BitBMP(), ICOReader::read8BitBMP(), read_dib_body(), read_pbm_body(), read_pbm_header(), read_xpm_string(), readAll(), readBMPInfoHeader(), QHttpNetworkReplyPrivate::readBodyFast(), QHttpNetworkReplyPrivate::readBodyVeryFast(), QDataStream::readBytes(), QVNCServer::readClient(), ICOReader::readColorTable(), QPatternist::QIODeviceDelegate::readData(), QFile::readData(), QAuthDevice::readData(), QHttpNetworkReplyPrivate::readHeader(), readIconDir(), readIconDirEntry(), readLineData(), QFile::readLineData(), QNetworkAccessFileBackend::readMoreFromFile(), QNonContiguousByteDeviceIoDeviceImpl::readPointer(), QDataStream::readRawData(), QHttpNetworkReplyPrivate::readReplyBodyChunked(), QHttpNetworkReplyPrivate::readReplyBodyRaw(), QHttpNetworkReplyPrivate::readStatus(), QPacketProtocolPrivate::readyToRead(), QDynamicFileResourceRoot::registerSelf(), QFile::rename(), QGIFFormat::scan(), QZipReaderPrivate::scanFiles(), QVNCServer::setEncodings(), QVNCServer::setPixelFormat(), QTransportAuth::setProcessKey(), QDataStream::skipRawData(), QFtpDTP::socketReadyRead(), QSslSocketBackendPrivate::transmit(), ungetChar(), QNetworkDiskCache::updateMetaData(), and QPdfEnginePrivate::writeCompressed().

792 {
793  Q_D(QIODevice);
794 
795 #if defined QIODEVICE_DEBUG
796  printf("%p QIODevice::read(%p, %d), d->pos = %d, d->buffer.size() = %d\n",
797  this, data, int(maxSize), int(d->pos), int(d->buffer.size()));
798 #endif
799 
800  // Short circuit for getChar()
801  if (maxSize == 1) {
802  int chint;
803  while ((chint = d->buffer.getChar()) != -1) {
804  ++(*d->pPos);
805 
806  char c = char(uchar(chint));
807  if (c == '\r' && (d->openMode & Text))
808  continue;
809  *data = c;
810 #if defined QIODEVICE_DEBUG
811  printf("%p \tread 0x%hhx (%c) returning 1 (shortcut)\n", this,
812  int(c), isprint(c) ? c : '?');
813 #endif
814  return qint64(1);
815  }
816  }
817 
818  CHECK_MAXLEN(read, qint64(-1));
819  qint64 readSoFar = 0;
820  bool moreToRead = true;
821  do {
822  // Try reading from the buffer.
823  int lastReadChunkSize = d->buffer.read(data, maxSize);
824  if (lastReadChunkSize > 0) {
825  *d->pPos += lastReadChunkSize;
826  readSoFar += lastReadChunkSize;
827  // fast exit when satisfied by buffer
828  if (lastReadChunkSize == maxSize && !(d->openMode & Text))
829  return readSoFar;
830 
831  data += lastReadChunkSize;
832  maxSize -= lastReadChunkSize;
833 #if defined QIODEVICE_DEBUG
834  printf("%p \treading %d bytes from buffer into position %d\n", this, lastReadChunkSize,
835  int(readSoFar) - lastReadChunkSize);
836 #endif
837  } else {
838  if (d->firstRead) {
839  // this is the first time the file has been read, check it's valid and set up pos pointers
840  // for fast pos updates.
841  CHECK_READABLE(read, qint64(-1));
842  d->firstRead = false;
843  if (d->isSequential()) {
844  d->pPos = &d->seqDumpPos;
845  d->pDevicePos = &d->seqDumpPos;
846  }
847  }
848 
849  if (!maxSize)
850  return readSoFar;
851 
852  if ((d->openMode & Unbuffered) == 0 && maxSize < QIODEVICE_BUFFERSIZE) {
853  // In buffered mode, we try to fill up the QIODevice buffer before
854  // we do anything else.
855  // buffer is empty at this point, try to fill it
856  int bytesToBuffer = QIODEVICE_BUFFERSIZE;
857  char *writePointer = d->buffer.reserve(bytesToBuffer);
858 
859  // Make sure the device is positioned correctly.
860  if (d->pos != d->devicePos && !d->isSequential() && !seek(d->pos))
861  return readSoFar ? readSoFar : qint64(-1);
862  qint64 readFromDevice = readData(writePointer, bytesToBuffer);
863  d->buffer.chop(bytesToBuffer - (readFromDevice < 0 ? 0 : int(readFromDevice)));
864 
865  if (readFromDevice > 0) {
866  *d->pDevicePos += readFromDevice;
867 #if defined QIODEVICE_DEBUG
868  printf("%p \treading %d from device into buffer\n", this, int(readFromDevice));
869 #endif
870 
871  if (!d->buffer.isEmpty()) {
872  lastReadChunkSize = d->buffer.read(data, maxSize);
873  readSoFar += lastReadChunkSize;
874  data += lastReadChunkSize;
875  maxSize -= lastReadChunkSize;
876  *d->pPos += lastReadChunkSize;
877 #if defined QIODEVICE_DEBUG
878  printf("%p \treading %d bytes from buffer at position %d\n", this,
879  lastReadChunkSize, int(readSoFar));
880 #endif
881  }
882  }
883  }
884  }
885 
886  // If we need more, try reading from the device.
887  if (maxSize > 0) {
888  // Make sure the device is positioned correctly.
889  if (d->pos != d->devicePos && !d->isSequential() && !seek(d->pos))
890  return readSoFar ? readSoFar : qint64(-1);
891  qint64 readFromDevice = readData(data, maxSize);
892 #if defined QIODEVICE_DEBUG
893  printf("%p \treading %d bytes from device (total %d)\n", this, int(readFromDevice), int(readSoFar));
894 #endif
895  if (readFromDevice == -1 && readSoFar == 0) {
896  // error and we haven't read anything: return immediately
897  return -1;
898  }
899  if (readFromDevice > 0) {
900  lastReadChunkSize += int(readFromDevice);
901  readSoFar += readFromDevice;
902  data += readFromDevice;
903  maxSize -= readFromDevice;
904  *d->pPos += readFromDevice;
905  *d->pDevicePos += readFromDevice;
906  }
907  }
908  // Best attempt has been made to read data, don't try again except for text mode adjustment below
909  moreToRead = false;
910 
911  if (readSoFar && d->openMode & Text) {
912  char *readPtr = data - lastReadChunkSize;
913  const char *endPtr = data;
914 
915  if (readPtr < endPtr) {
916  // optimization to avoid initial self-assignment
917  while (*readPtr != '\r') {
918  if (++readPtr == endPtr)
919  return readSoFar;
920  }
921 
922  char *writePtr = readPtr;
923 
924  while (readPtr < endPtr) {
925  char ch = *readPtr++;
926  if (ch != '\r')
927  *writePtr++ = ch;
928  else {
929  --readSoFar;
930  --data;
931  ++maxSize;
932  }
933  }
934 
935  // Make sure we get more data if there is room for more. This
936  // is very important for when someone seeks to the start of a
937  // '\r\n' and reads one character - they should get the '\n'.
938  moreToRead = (readPtr != writePtr);
939  }
940  }
941  } while (moreToRead);
942 
943 #if defined QIODEVICE_DEBUG
944  printf("%p \treturning %d, d->pos == %d, d->buffer.size() == %d\n", this,
945  int(readSoFar), int(d->pos), d->buffer.size());
946  debugBinaryString(data - readSoFar, readSoFar);
947 #endif
948  return readSoFar;
949 }
double d
Definition: qnumeric_p.h:62
unsigned char c[8]
Definition: qnumeric_p.h:62
#define CHECK_MAXLEN(function, returnType)
Definition: qiodevice.cpp:89
#define QIODEVICE_BUFFERSIZE
Definition: qiodevice_p.h:68
#define Q_D(Class)
Definition: qglobal.h:2482
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read...
Definition: qiodevice.cpp:791
unsigned char uchar
Definition: qglobal.h:994
static const char * data(const QByteArray &arr)
__int64 qint64
Definition: qglobal.h:942
virtual qint64 readData(char *data, qint64 maxlen)=0
Reads up to maxSize bytes from the device into data, and returns the number of bytes read or -1 if an...
#define CHECK_READABLE(function, returnType)
Definition: qiodevice.cpp:107
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66
virtual bool seek(qint64 pos)
For random-access devices, this function sets the current position to pos, returning true on success...
Definition: qiodevice.cpp:659
The Text item allows you to add formatted text to a scene.

◆ read() [2/2]

QByteArray QIODevice::read ( qint64  maxSize)

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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.

Definition at line 968 of file qiodevice.cpp.

969 {
970  Q_D(QIODevice);
971  QByteArray result;
972 
973  CHECK_MAXLEN(read, result);
974 
975 #if defined QIODEVICE_DEBUG
976  printf("%p QIODevice::read(%d), d->pos = %d, d->buffer.size() = %d\n",
977  this, int(maxSize), int(d->pos), int(d->buffer.size()));
978 #else
979  Q_UNUSED(d);
980 #endif
981 
982  if (maxSize != qint64(int(maxSize))) {
983  qWarning("QIODevice::read: maxSize argument exceeds QByteArray size limit");
984  maxSize = INT_MAX;
985  }
986 
987  qint64 readBytes = 0;
988  if (maxSize) {
989  result.resize(int(maxSize));
990  if (!result.size()) {
991  // If resize fails, read incrementally.
992  qint64 readResult;
993  do {
994  result.resize(int(qMin(maxSize, result.size() + QIODEVICE_BUFFERSIZE)));
995  readResult = read(result.data() + readBytes, result.size() - readBytes);
996  if (readResult > 0 || readBytes == 0)
997  readBytes += readResult;
998  } while (readResult == QIODEVICE_BUFFERSIZE);
999  } else {
1000  readBytes = read(result.data(), result.size());
1001  }
1002  }
1003 
1004  if (readBytes <= 0)
1005  result.clear();
1006  else
1007  result.resize(int(readBytes));
1008 
1009  return result;
1010 }
double d
Definition: qnumeric_p.h:62
Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)
Definition: qglobal.h:1215
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
#define CHECK_MAXLEN(function, returnType)
Definition: qiodevice.cpp:89
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
#define QIODEVICE_BUFFERSIZE
Definition: qiodevice_p.h:68
#define Q_D(Class)
Definition: qglobal.h:2482
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read...
Definition: qiodevice.cpp:791
Q_CORE_EXPORT void qWarning(const char *,...)
__int64 qint64
Definition: qglobal.h:942
void resize(int size)
Sets the size of the byte array to size bytes.
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729
#define INT_MAX
void clear()
Clears the contents of the byte array and makes it empty.

◆ readAll()

QByteArray QIODevice::readAll ( )

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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.

Definition at line 1025 of file qiodevice.cpp.

Referenced by QHttpPrivate::_q_slotReadyRead(), QFontDatabase::addApplicationFont(), QZipWriter::addFile(), QGLShader::compileSourceFile(), QPatternist::ExpressionFactory::createExpression(), QNetworkDiskCache::data(), QDeclarativeXMLHttpRequest::downloadProgress(), QDeclarativeInclude::finished(), QDeclarativeXMLHttpRequest::finished(), QSslCertificate::fromDevice(), QDirectFBPixmapData::fromFile(), QGLPixmapData::fromFile(), QSslCertificate::fromPath(), QFreetypeFace::getFace(), QDeclarativeInclude::include(), QSvgIOHandlerPrivate::load(), QPicture::load(), QDeclarativeDataLoader::load(), QAxScriptManager::load(), QRawFont::loadFromFile(), QTextBrowser::loadResource(), QTextDocument::loadResource(), QDeclarativeDataLoader::networkReplyFinished(), QDeclarativePixmapReader::networkRequestDone(), operator<<(), QDeclarativeDirParser::parse(), QDeclarativeWorkerScriptEnginePrivate::processLoad(), QSslCertificate::QSslCertificate(), QSslKey::QSslKey(), qt_getDefaultFromHomePrinters(), qt_parse_pattern(), QFtpDTP::readAll(), QProcess::readAllStandardError(), QProcess::readAllStandardOutput(), registerFont(), QDeclarativeFontObject::replyFinished(), QPatternist::AccelTreeResourceLoader::retrieveUnparsedText(), QSslSocket::setLocalCertificate(), QSslSocket::setPrivateKey(), QNetworkReplyImplPrivate::setup(), QFtpDTP::socketConnectionClosed(), QFtpDTP::socketReadyRead(), QConfFileSettingsPrivate::syncConfFile(), QSocks5Authenticator::unSeal(), QDeclarativeInclude::worker_include(), and QSvgIconEngine::write().

1026 {
1027  Q_D(QIODevice);
1028 #if defined QIODEVICE_DEBUG
1029  printf("%p QIODevice::readAll(), d->pos = %d, d->buffer.size() = %d\n",
1030  this, int(d->pos), int(d->buffer.size()));
1031 #endif
1032 
1033  QByteArray result;
1034  qint64 readBytes = 0;
1035 
1036  // flush internal read buffer
1037  if (!(d->openMode & Text) && !d->buffer.isEmpty()) {
1038  result = d->buffer.readAll();
1039  readBytes = result.size();
1040  d->pos += readBytes;
1041  }
1042 
1043  qint64 theSize;
1044  if (d->isSequential() || (theSize = size()) == 0) {
1045  // Size is unknown, read incrementally.
1046  qint64 readResult;
1047  do {
1048  result.resize(result.size() + QIODEVICE_BUFFERSIZE);
1049  readResult = read(result.data() + readBytes, result.size() - readBytes);
1050  if (readResult > 0 || readBytes == 0)
1051  readBytes += readResult;
1052  } while (readResult > 0);
1053  } else {
1054  // Read it all in one go.
1055  // If resize fails, don't read anything.
1056  result.resize(int(readBytes + theSize - d->pos));
1057  readBytes += read(result.data() + readBytes, result.size() - readBytes);
1058  }
1059 
1060  if (readBytes <= 0)
1061  result.clear();
1062  else
1063  result.resize(int(readBytes));
1064 
1065  return result;
1066 }
double d
Definition: qnumeric_p.h:62
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
#define QIODEVICE_BUFFERSIZE
Definition: qiodevice_p.h:68
#define Q_D(Class)
Definition: qglobal.h:2482
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read...
Definition: qiodevice.cpp:791
__int64 qint64
Definition: qglobal.h:942
void resize(int size)
Sets the size of the byte array to size bytes.
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66
void clear()
Clears the contents of the byte array and makes it empty.
The Text item allows you to add formatted text to a scene.

◆ readChannelFinished

QIODevice::readChannelFinished ( )
signal

This signal is emitted when the input (reading) stream is closed in this device.

Since
4.4

It is emitted as soon as the closing is detected, which means that there might still be data available for reading with read().

See also
atEnd(), read()

Referenced by QAbstractSocket::disconnectFromHostImplementation(), and QPatternist::QIODeviceDelegate::QIODeviceDelegate().

◆ readData()

qint64 QIODevice::readData ( char *  data,
qint64  maxSize 
)
protectedpure virtual

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

If there are no bytes to be read and there can never be more bytes available (examples include socket closed, pipe closed, sub-process finished), this function returns -1.

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

When reimplementing this function it is important that this function reads all the required data before returning. This is required in order for QDataStream to be able to operate on the class. QDataStream assumes all the requested information was read and therefore does not retry reading if there was a problem.

See also
read() readLine() writeData()

Implemented in QtMultimediaInternal::MacInputDevice, MacOutputDevice, QDisabledNetworkReply, QAuthDevice, QProcess, QFile, QAbstractSocket, QSslSocket, QUnixSocket, QByteDeviceWrappingIoDevice, OutputPrivate, InputPrivate, QHttpMultiPartIODevice, InputPrivate, OutputPrivate, QLocalSocket, QBuffer, QPatternist::QIODeviceDelegate, QNetworkReplyImpl, QNetworkReplyFileImpl, QNetworkReplyDataImpl, and QOstDevice.

Referenced by read(), and QUnixSocket::read().

◆ readLine() [1/2]

qint64 QIODevice::readLine ( char *  data,
qint64  maxSize 
)

This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes, stores the characters in data, and returns the number of bytes read.

If a line could not be read but no error ocurred, this function returns 0. If an error occurs, this function returns the length of what could be read, or -1 if nothing was read.

A terminating '\0' byte is always appended to data, so maxSize must be larger than 1.

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

  • The first '
    ' character is read.
  • maxSize - 1 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];
qint64 lineLength = file.readLine(buf, sizeof(buf));
if (lineLength != -1) {
// the line is available in buf
}
}

The newline character ('
') is included in the buffer. If a newline is not encountered before maxSize - 1 bytes are read, a newline will not be inserted into the buffer. On windows newline characters are replaced with '
'.

This function calls readLineData(), which is implemented using repeated calls to getChar(). You can provide a more efficient implementation by reimplementing readLineData() in your own subclass.

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

Definition at line 1110 of file qiodevice.cpp.

Referenced by QHttpPrivate::_q_slotReadyRead(), QBenchmarkValgrindUtils::extractResult(), QTextStreamPrivate::fillReadBuffer(), fontFile(), fontPath(), QHostInfo::localDomainName(), QDeclarativeGridScaledImage::QDeclarativeGridScaledImage(), qt_getLprPrinters(), qt_parseEtcLpPrinters(), qt_parseNsswitchConf(), qt_parsePrintcap(), qt_parsePrintersConf(), qt_read_xpm_image_or_array(), read_pbm_int(), read_xbm_body(), read_xbm_header(), readLine(), QFtpPI::readyRead(), QFtpDTP::socketReadyRead(), and QCoreApplicationData::~QCoreApplicationData().

1111 {
1112  Q_D(QIODevice);
1113  if (maxSize < 2) {
1114  qWarning("QIODevice::readLine: Called with maxSize < 2");
1115  return qint64(-1);
1116  }
1117 
1118 #if defined QIODEVICE_DEBUG
1119  printf("%p QIODevice::readLine(%p, %d), d->pos = %d, d->buffer.size() = %d\n",
1120  this, data, int(maxSize), int(d->pos), int(d->buffer.size()));
1121 #endif
1122 
1123  // Leave room for a '\0'
1124  --maxSize;
1125 
1126  const bool sequential = d->isSequential();
1127 
1128  qint64 readSoFar = 0;
1129  if (!d->buffer.isEmpty()) {
1130  readSoFar = d->buffer.readLine(data, maxSize);
1131  if (!sequential)
1132  d->pos += readSoFar;
1133 #if defined QIODEVICE_DEBUG
1134  printf("%p \tread from buffer: %d bytes, last character read: %hhx\n", this,
1135  int(readSoFar), data[int(readSoFar) - 1]);
1136  if (readSoFar)
1137  debugBinaryString(data, int(readSoFar));
1138 #endif
1139 #if defined(Q_OS_SYMBIAN)
1140  // Open C fgets strips '\r' but readSoFar gets returned as if it was still there
1141  if ((d->openMode & Text) &&
1142  readSoFar > 1 &&
1143  data[readSoFar - 1] == '\0' &&
1144  data[readSoFar - 2] == '\n') {
1145  --readSoFar;
1146  }
1147 #endif
1148  if (readSoFar && data[readSoFar - 1] == '\n') {
1149  if (d->openMode & Text) {
1150  // QRingBuffer::readLine() isn't Text aware.
1151  if (readSoFar > 1 && data[readSoFar - 2] == '\r') {
1152  --readSoFar;
1153  data[readSoFar - 1] = '\n';
1154  }
1155  }
1156  data[readSoFar] = '\0';
1157  return readSoFar;
1158  }
1159  }
1160 
1161  if (d->pos != d->devicePos && !sequential && !seek(d->pos))
1162  return qint64(-1);
1163  d->baseReadLineDataCalled = false;
1164  qint64 readBytes = readLineData(data + readSoFar, maxSize - readSoFar);
1165 #if defined QIODEVICE_DEBUG
1166  printf("%p \tread from readLineData: %d bytes, readSoFar = %d bytes\n", this,
1167  int(readBytes), int(readSoFar));
1168  if (readBytes > 0) {
1169  debugBinaryString(data, int(readSoFar + readBytes));
1170  }
1171 #endif
1172  if (readBytes < 0) {
1173  data[readSoFar] = '\0';
1174  return readSoFar ? readSoFar : -1;
1175  }
1176  readSoFar += readBytes;
1177  if (!d->baseReadLineDataCalled && !sequential) {
1178  d->pos += readBytes;
1179  // If the base implementation was not called, then we must
1180  // assume the device position is invalid and force a seek.
1181  d->devicePos = qint64(-1);
1182  }
1183  data[readSoFar] = '\0';
1184 
1185  if (d->openMode & Text) {
1186 #if defined(Q_OS_SYMBIAN)
1187  // Open C fgets strips '\r' but readSoFar gets returned as if it was still there
1188  if (readSoFar > 1 && data[readSoFar - 1] == '\0' && data[readSoFar - 2] == '\n') {
1189  --readSoFar;
1190  }
1191 #endif
1192  if (readSoFar > 1 && data[readSoFar - 1] == '\n' && data[readSoFar - 2] == '\r') {
1193  data[readSoFar - 2] = '\n';
1194  data[readSoFar - 1] = '\0';
1195  --readSoFar;
1196  }
1197  }
1198 
1199 #if defined QIODEVICE_DEBUG
1200  printf("%p \treturning %d, d->pos = %d, d->buffer.size() = %d, size() = %d\n",
1201  this, int(readSoFar), int(d->pos), d->buffer.size(), int(size()));
1202  debugBinaryString(data, int(readSoFar));
1203 #endif
1204  return readSoFar;
1205 }
double d
Definition: qnumeric_p.h:62
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
#define Q_D(Class)
Definition: qglobal.h:2482
virtual qint64 readLineData(char *data, qint64 maxlen)
Reads up to maxSize characters into data and returns the number of characters read.
Definition: qiodevice.cpp:1285
Q_CORE_EXPORT void qWarning(const char *,...)
static const char * data(const QByteArray &arr)
__int64 qint64
Definition: qglobal.h:942
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66
virtual bool seek(qint64 pos)
For random-access devices, this function sets the current position to pos, returning true on success...
Definition: qiodevice.cpp:659
The Text item allows you to add formatted text to a scene.

◆ readLine() [2/2]

QByteArray QIODevice::readLine ( qint64  maxSize = 0)

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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.

Definition at line 1220 of file qiodevice.cpp.

1221 {
1222  Q_D(QIODevice);
1223  QByteArray result;
1224 
1225  CHECK_MAXLEN(readLine, result);
1226 
1227 #if defined QIODEVICE_DEBUG
1228  printf("%p QIODevice::readLine(%d), d->pos = %d, d->buffer.size() = %d\n",
1229  this, int(maxSize), int(d->pos), int(d->buffer.size()));
1230 #else
1231  Q_UNUSED(d);
1232 #endif
1233 
1234  if (maxSize > INT_MAX) {
1235  qWarning("QIODevice::read: maxSize argument exceeds QByteArray size limit");
1236  maxSize = INT_MAX;
1237  }
1238 
1239  result.resize(int(maxSize));
1240  qint64 readBytes = 0;
1241  if (!result.size()) {
1242  // If resize fails or maxSize == 0, read incrementally
1243  if (maxSize == 0)
1244  maxSize = INT_MAX;
1245 
1246  // The first iteration needs to leave an extra byte for the terminating null
1247  result.resize(1);
1248 
1249  qint64 readResult;
1250  do {
1251  result.resize(int(qMin(maxSize, result.size() + QIODEVICE_BUFFERSIZE)));
1252  readResult = readLine(result.data() + readBytes, result.size() - readBytes);
1253  if (readResult > 0 || readBytes == 0)
1254  readBytes += readResult;
1255  } while (readResult == QIODEVICE_BUFFERSIZE
1256  && result[int(readBytes - 1)] != '\n');
1257  } else
1258  readBytes = readLine(result.data(), result.size());
1259 
1260  if (readBytes <= 0)
1261  result.clear();
1262  else
1263  result.resize(readBytes);
1264 
1265  return result;
1266 }
double d
Definition: qnumeric_p.h:62
Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)
Definition: qglobal.h:1215
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
#define CHECK_MAXLEN(function, returnType)
Definition: qiodevice.cpp:89
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
#define QIODEVICE_BUFFERSIZE
Definition: qiodevice_p.h:68
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qWarning(const char *,...)
__int64 qint64
Definition: qglobal.h:942
qint64 readLine(char *data, qint64 maxlen)
This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes...
Definition: qiodevice.cpp:1110
void resize(int size)
Sets the size of the byte array to size bytes.
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729
#define INT_MAX
void clear()
Clears the contents of the byte array and makes it empty.

◆ readLineData()

qint64 QIODevice::readLineData ( char *  data,
qint64  maxSize 
)
protectedvirtual

Reads up to maxSize characters into data and returns the number of characters read.

This function is called by readLine(), and provides its base implementation, using getChar(). Buffered devices can improve the performance of readLine() by reimplementing this function.

readLine() appends a '\0' byte to data; readLineData() does not need to do this.

If you reimplement this function, be careful to return the correct value: it should return the number of bytes read in this line, including the terminating newline, or 0 if there is no line to be read at this point. If an error occurs, it should return -1 if and only if no bytes were read. Reading past EOF is considered an error.

Reimplemented in QFile, and QAbstractSocket.

Definition at line 1285 of file qiodevice.cpp.

Referenced by readLine(), QAbstractSocket::readLineData(), and QFile::readLineData().

1286 {
1287  Q_D(QIODevice);
1288  qint64 readSoFar = 0;
1289  char c;
1290  int lastReadReturn = 0;
1291  d->baseReadLineDataCalled = true;
1292 
1293  while (readSoFar < maxSize && (lastReadReturn = read(&c, 1)) == 1) {
1294  *data++ = c;
1295  ++readSoFar;
1296  if (c == '\n')
1297  break;
1298  }
1299 
1300 #if defined QIODEVICE_DEBUG
1301  printf("%p QIODevice::readLineData(%p, %d), d->pos = %d, d->buffer.size() = %d, returns %d\n",
1302  this, data, int(maxSize), int(d->pos), int(d->buffer.size()), int(readSoFar));
1303 #endif
1304  if (lastReadReturn != 1 && readSoFar == 0)
1305  return isSequential() ? lastReadReturn : -1;
1306  return readSoFar;
1307 }
double d
Definition: qnumeric_p.h:62
unsigned char c[8]
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read...
Definition: qiodevice.cpp:791
static const char * data(const QByteArray &arr)
__int64 qint64
Definition: qglobal.h:942
virtual bool isSequential() const
Returns true if this device is sequential; otherwise returns false.
Definition: qiodevice.cpp:454
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66

◆ readyRead

QIODevice::readyRead ( )
signal

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

It will only be emitted again once new data is available, such as when a new payload of network data has arrived on your network socket, or when a new block of data has been appended to your device.

readyRead() is not emitted recursively; if you reenter the event loop or call waitForReadyRead() inside a slot connected to the readyRead() signal, the signal will not be reemitted (although waitForReadyRead() may still return true).

Note for developers implementing classes derived from QIODevice: you should always emit readyRead() when new data has arrived (do not emit it only because there's data still to be read in your buffers). Do not emit readyRead() in other conditions.

See also
bytesWritten()

Referenced by QAuthDevice::authorizeMessage(), QAuthDevice::QAuthDevice(), QByteDeviceWrappingIoDevice::QByteDeviceWrappingIoDevice(), QPatternist::QIODeviceDelegate::QIODeviceDelegate(), and QUnixSocketPrivate::readActivated().

◆ reset()

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).

Note that when using a QTextStream on a QFile, calling reset() on the QFile will not have the expected result because QTextStream buffers the file. Use the QTextStream::seek() function instead.

See also
seek()

Reimplemented in QByteDeviceWrappingIoDevice, QHttpMultiPartIODevice, and QPatternist::QIODeviceDelegate.

Definition at line 732 of file qiodevice.cpp.

Referenced by QMacPasteboardMimeVCard::convertFromMime(), QPdf::ByteStream::operator<<(), QPdf::ByteStream::prepareBuffer(), QPatternist::QIODeviceDelegate::reset(), QNonContiguousByteDeviceIoDeviceImpl::reset(), and QPdf::ByteStream::stream().

733 {
734 #if defined QIODEVICE_DEBUG
735  printf("%p QIODevice::reset()\n", this);
736 #endif
737  return seek(0);
738 }
virtual bool seek(qint64 pos)
For random-access devices, this function sets the current position to pos, returning true on success...
Definition: qiodevice.cpp:659

◆ seek()

bool QIODevice::seek ( qint64  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.

When subclassing QIODevice, you must call QIODevice::seek() at the start of your function to ensure integrity with QIODevice's built-in buffer. The base implementation always returns true.

See also
pos(), isSequential()

Reimplemented in QAuthDevice, QFile, QBuffer, and QPatternist::QIODeviceDelegate.

Definition at line 659 of file qiodevice.cpp.

Referenced by QHttpPrivate::_q_slotConnected(), QZipWriterPrivate::addEntry(), QTiffHandler::canRead(), QXbmHandler::canRead(), ICOReader::canRead(), QZipWriter::close(), createReadHandlerHelper(), QAudioOutputPrivate::deviceReady(), QPicture::exec(), QZipReader::fileData(), QAudioOutputPrivate::freeBlocks(), ICOReader::iconAt(), iod_read_fn(), QPdf::ByteStream::operator<<(), QTiffHandler::option(), QtIcoHandler::option(), QPictureIO::pictureFormat(), QPicture::play(), QPdf::ByteStream::prepareBuffer(), qt_fill_input_buffer(), qt_term_source(), QTgaFile::QTgaFile(), qtiffSeekProc(), read(), read_dib_body(), ICOReader::readBMPHeader(), ICOReader::readIconEntry(), QTgaFile::readImage(), readLine(), reset(), QNonContiguousByteDeviceIoDeviceImpl::reset(), QGIFFormat::scan(), QZipReaderPrivate::scanFiles(), QPatternist::QIODeviceDelegate::seek(), QBuffer::seek(), QFile::seek(), QDataStream::skipRawData(), QFile::symLinkTarget(), and write().

660 {
661  Q_D(QIODevice);
662  if (d->openMode == NotOpen) {
663  qWarning("QIODevice::seek: The device is not open");
664  return false;
665  }
666  if (pos < 0) {
667  qWarning("QIODevice::seek: Invalid pos: %d", int(pos));
668  return false;
669  }
670 
671 #if defined QIODEVICE_DEBUG
672  printf("%p QIODevice::seek(%d), before: d->pos = %d, d->buffer.size() = %d\n",
673  this, int(pos), int(d->pos), d->buffer.size());
674 #endif
675 
676  qint64 offset = pos - d->pos;
677  if (!d->isSequential()) {
678  d->pos = pos;
679  d->devicePos = pos;
680  }
681 
682  if (offset < 0
683  || offset >= qint64(d->buffer.size()))
684  // When seeking backwards, an operation that is only allowed for
685  // random-access devices, the buffer is cleared. The next read
686  // operation will then refill the buffer. We can optimize this, if we
687  // find that seeking backwards becomes a significant performance hit.
688  d->buffer.clear();
689  else if (!d->buffer.isEmpty())
690  d->buffer.skip(int(offset));
691 
692 #if defined QIODEVICE_DEBUG
693  printf("%p \tafter: d->pos == %d, d->buffer.size() == %d\n", this, int(d->pos),
694  d->buffer.size());
695 #endif
696  return true;
697 }
double d
Definition: qnumeric_p.h:62
virtual qint64 pos() const
For random-access devices, this function returns the position that data is written to or read from...
Definition: qiodevice.cpp:624
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qWarning(const char *,...)
__int64 qint64
Definition: qglobal.h:942
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66

◆ setErrorString()

void QIODevice::setErrorString ( const QString str)
protected

◆ setOpenMode()

void QIODevice::setOpenMode ( OpenMode  openMode)
protected

Sets the OpenMode of the device to openMode.

Call this function to set the open mode if the flags change after the device has been opened.

See also
openMode() OpenMode

Definition at line 477 of file qiodevice.cpp.

Referenced by QUnixSocket::abort(), QUnixSocket::connect(), QPatternist::QIODeviceDelegate::open(), QTemporaryFile::open(), QPatternist::QIODeviceDelegate::QIODeviceDelegate(), QUnixSocket::QUnixSocket(), and QUnixSocket::setSocketDescriptor().

478 {
479  Q_D(QIODevice);
480 #if defined QIODEVICE_DEBUG
481  printf("%p QIODevice::setOpenMode(0x%x)\n", this, int(openMode));
482 #endif
483  d->openMode = openMode;
484  d->accessMode = QIODevicePrivate::Unset;
485  d->firstRead = true;
486  if (!isReadable())
487  d->buffer.clear();
488 }
double d
Definition: qnumeric_p.h:62
bool isReadable() const
Returns true if data can be read from the device; otherwise returns false.
Definition: qiodevice.cpp:544
#define Q_D(Class)
Definition: qglobal.h:2482
OpenMode openMode() const
Returns the mode in which the device has been opened; i.e.
Definition: qiodevice.cpp:465
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66

◆ setTextModeEnabled()

void QIODevice::setTextModeEnabled ( bool  enabled)

If enabled is true, this function sets the Text flag on the device; otherwise the Text flag is removed.

This feature is useful for classes that provide custom end-of-line handling on a QIODevice.

The IO device should be opened before calling this function.

See also
open(), setOpenMode()

Definition at line 499 of file qiodevice.cpp.

Referenced by QTextStreamPrivate::fillReadBuffer(), and QTextStreamPrivate::flushWriteBuffer().

500 {
501  Q_D(QIODevice);
502  if (!isOpen()) {
503  qWarning("QIODevice::setTextModeEnabled: The device is not open");
504  return;
505  }
506  if (enabled)
507  d->openMode |= Text;
508  else
509  d->openMode &= ~Text;
510 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530
Q_CORE_EXPORT void qWarning(const char *,...)
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66
#define enabled
The Text item allows you to add formatted text to a scene.

◆ size()

qint64 QIODevice::size ( ) const
virtual

For open random-access devices, this function returns the size of the device.

For open sequential devices, bytesAvailable() is returned.

If the device is closed, the size returned will not reflect the actual size of the device.

See also
isSequential(), pos()

Reimplemented in QByteDeviceWrappingIoDevice, QFile, QHttpMultiPartIODevice, QBuffer, QPatternist::QIODeviceDelegate, QNetworkReplyFileImpl, and QNetworkReplyDataImpl.

Definition at line 642 of file qiodevice.cpp.

Referenced by QHttpPrivate::_q_slotConnected(), QFtpPrivate::_q_startNextCommand(), atEnd(), bytesAvailable(), QProcess::bytesToWrite(), QNetworkAccessManager::createRequest(), QPSPrintEnginePrivate::flushPage(), iod_read_fn(), QDeclarativeDataLoader::load(), open(), QHttpPrivate::postMoreData(), QPdf::ByteStream::prepareBuffer(), QFtp::put(), QTgaFile::QTgaFile(), qtiffSeekProc(), readAll(), QUnixSocket::readData(), readLine(), QZipReaderPrivate::scanFiles(), QNetworkAccessHttpBackend::sendCacheContents(), QNetworkReply::setReadBufferSize(), QAbstractSocket::setReadBufferSize(), QUnixSocket::setReadBufferSize(), QUnixSocket::setRightsBufferSize(), QPatternist::QIODeviceDelegate::size(), QNonContiguousByteDeviceIoDeviceImpl::size(), QDataStream::skipRawData(), QFile::symLinkTarget(), and QAbstractSocket::writeData().

643 {
644  return d_func()->isSequential() ? bytesAvailable() : qint64(0);
645 }
__int64 qint64
Definition: qglobal.h:942
virtual qint64 bytesAvailable() const
Returns the number of bytes that are available for reading.
Definition: qiodevice.cpp:752

◆ ungetChar()

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.

If c was not previously read from the device, the behavior is undefined.

Definition at line 1462 of file qiodevice.cpp.

Referenced by ICOReader::canRead(), QSocks5SocketEnginePrivate::parseRequestMethodReply(), qt_read_xpm_image_or_array(), and read_xpm_body().

1463 {
1464  Q_D(QIODevice);
1466 
1467 #if defined QIODEVICE_DEBUG
1468  printf("%p QIODevice::ungetChar(0x%hhx '%c')\n", this, c, isprint(c) ? c : '?');
1469 #endif
1470 
1471  d->buffer.ungetChar(c);
1472  if (!d->isSequential())
1473  --d->pos;
1474 }
double d
Definition: qnumeric_p.h:62
unsigned char c[8]
Definition: qnumeric_p.h:62
#define Q_VOID
Definition: qiodevice.cpp:87
#define Q_D(Class)
Definition: qglobal.h:2482
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read...
Definition: qiodevice.cpp:791
#define CHECK_READABLE(function, returnType)
Definition: qiodevice.cpp:107
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66

◆ waitForBytesWritten()

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.

If msecs is -1, this function will not time out. For unbuffered devices, it returns immediately.

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.

If called from within a slot connected to the bytesWritten() signal, bytesWritten() will not be reemitted.

Reimplement this function to provide a blocking API for a custom device. The default implementation does nothing, and returns false.

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

Reimplemented in QUnixSocket, QAbstractSocket, QProcess, QSslSocket, QLocalSocket, and QPatternist::QIODeviceDelegate.

Definition at line 1648 of file qiodevice.cpp.

Referenced by QUnixSocket::read(), and QPatternist::QIODeviceDelegate::waitForBytesWritten().

1649 {
1650  Q_UNUSED(msecs);
1651  return false;
1652 }
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729

◆ waitForReadyRead()

bool QIODevice::waitForReadyRead ( int  msecs)
virtual

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

If msecs is -1, this function will not time out.

Returns true if new 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.

If called from within a slot connected to the readyRead() signal, readyRead() will not be reemitted.

Reimplement this function to provide a blocking API for a custom device. The default implementation does nothing, and returns false.

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

Reimplemented in QUnixSocket, QAbstractSocket, QProcess, QSslSocket, QLocalSocket, QPatternist::QIODeviceDelegate, and QOstDevice.

Definition at line 1616 of file qiodevice.cpp.

Referenced by QXmlInputSource::fetchData(), QUnixSocket::read(), QPacketProtocol::waitForReadyRead(), and QPatternist::QIODeviceDelegate::waitForReadyRead().

1617 {
1618  Q_UNUSED(msecs);
1619  return false;
1620 }
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729

◆ write() [1/3]

qint64 QIODevice::write ( const char *  data,
qint64  maxSize 
)

Writes at most maxSize 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() writeData()

Definition at line 1342 of file qiodevice.cpp.

Referenced by QHttpPrivate::_q_slotConnected(), QHttpPrivate::_q_slotReadyRead(), QFtpPI::abort(), QZipWriterPrivate::addEntry(), QNetworkReplyImplPrivate::appendDownstreamData(), QNetworkReplyImplPrivate::appendDownstreamDataDownloadBuffer(), QSocks5PasswordAuthenticator::beginAuthenticate(), buttonChange(), QVNCCursor::clearClientCursor(), QZipWriter::close(), QTemporaryFile::createLocalFile(), QGraphicsAnchorLayoutPrivate::dumpGraph(), dumpOutput(), QPdfEnginePrivate::embedFont(), QPSPrintEnginePrivate::emitHeader(), QPSPrintEnginePrivate::emitPages(), QtopiaPrintEngine::end(), QZipReader::extractAll(), QTextStreamPrivate::flushWriteBuffer(), QAudioInputPrivate::freeBlocks(), QTestLiteStaticInfoPrivate::initializeSupportedAtoms(), QVNCServer::newConnection(), QPdf::ByteStream::operator<<(), QDataStream::operator<<(), QPatternist::XsdStateMachine< XsdSchemaToken::NodeName >::outputGraph(), QHttpNetworkConnectionChannel::pipelineFlush(), QHttpPrivate::postMoreData(), QPdf::ByteStream::prepareBuffer(), qpiw_write_fn(), qt_empty_output_buffer(), qt_get_net_supported(), qt_get_net_virtual_roots(), qt_term_destination(), qt_write_dib(), qt_write_dibv5(), QVNCDirtyMap::QVNCDirtyMap(), qws_write_command(), qws_write_uint(), QAudioInputPrivate::read(), QUnixSocket::read(), QVNCServer::readClient(), registerFont(), QFile::rename(), QPicture::save(), QBuffer::seek(), QPacketProtocol::send(), QWaylandSelection::send(), QVNCCursor::sendClientCursor(), QHttpNetworkConnectionChannel::sendRequest(), QSocks5SocketEnginePrivate::sendRequestMethod(), QSslSocketBackendPrivate::startHandshake(), QFtpPI::startNextCmd(), QSslSocketBackendPrivate::transmit(), QNetworkDiskCache::updateMetaData(), QNetworkAccessFileBackend::uploadReadyReadSlot(), QPatternist::ColorOutputPrivate::write(), QVNCClientCursor::write(), ICOReader::write(), write(), QRfbRect::write(), QRfbPixelFormat::write(), QUnixSocket::write(), QRfbServerInit::write(), QRfbRawEncoder::write(), QRfbSingleColorHextile< SRC >::write(), QRfbDualColorHextile< SRC >::write(), QRfbMultiColorHextile< SRC >::write(), QRfbHextileEncoder< SRC >::write(), QXmlStreamWriterPrivate::write(), write_pbm_image(), write_xbm_image(), writeBMPInfoHeader(), QFtpDTP::writeData(), QAuthDevice::writeData(), writeIconDir(), writeIconDirEntry(), QConfFileSettingsPrivate::writeIniFile(), and QDataStream::writeRawData().

1343 {
1344  Q_D(QIODevice);
1345  CHECK_WRITABLE(write, qint64(-1));
1346  CHECK_MAXLEN(write, qint64(-1));
1347 
1348  const bool sequential = d->isSequential();
1349  // Make sure the device is positioned correctly.
1350  if (d->pos != d->devicePos && !sequential && !seek(d->pos))
1351  return qint64(-1);
1352 
1353 #ifdef Q_OS_WIN
1354  if (d->openMode & Text) {
1355  const char *endOfData = data + maxSize;
1356  const char *startOfBlock = data;
1357 
1358  qint64 writtenSoFar = 0;
1359 
1360  forever {
1361  const char *endOfBlock = startOfBlock;
1362  while (endOfBlock < endOfData && *endOfBlock != '\n')
1363  ++endOfBlock;
1364 
1365  qint64 blockSize = endOfBlock - startOfBlock;
1366  if (blockSize > 0) {
1367  qint64 ret = writeData(startOfBlock, blockSize);
1368  if (ret <= 0) {
1369  if (writtenSoFar && !sequential)
1370  d->buffer.skip(writtenSoFar);
1371  return writtenSoFar ? writtenSoFar : ret;
1372  }
1373  if (!sequential) {
1374  d->pos += ret;
1375  d->devicePos += ret;
1376  }
1377  writtenSoFar += ret;
1378  }
1379 
1380  if (endOfBlock == endOfData)
1381  break;
1382 
1383  qint64 ret = writeData("\r\n", 2);
1384  if (ret <= 0) {
1385  if (writtenSoFar && !sequential)
1386  d->buffer.skip(writtenSoFar);
1387  return writtenSoFar ? writtenSoFar : ret;
1388  }
1389  if (!sequential) {
1390  d->pos += ret;
1391  d->devicePos += ret;
1392  }
1393  ++writtenSoFar;
1394 
1395  startOfBlock = endOfBlock + 1;
1396  }
1397 
1398  if (writtenSoFar && !sequential)
1399  d->buffer.skip(writtenSoFar);
1400  return writtenSoFar;
1401  }
1402 #endif
1403 
1404  qint64 written = writeData(data, maxSize);
1405  if (written > 0) {
1406  if (!sequential) {
1407  d->pos += written;
1408  d->devicePos += written;
1409  }
1410  if (!d->buffer.isEmpty() && !sequential)
1411  d->buffer.skip(written);
1412  }
1413  return written;
1414 }
double d
Definition: qnumeric_p.h:62
const int blockSize
#define CHECK_WRITABLE(function, returnType)
Definition: qiodevice.cpp:97
#define CHECK_MAXLEN(function, returnType)
Definition: qiodevice.cpp:89
virtual qint64 writeData(const char *data, qint64 len)=0
Writes up to maxSize bytes from data to the device.
#define Q_D(Class)
Definition: qglobal.h:2482
static const char * data(const QByteArray &arr)
__int64 qint64
Definition: qglobal.h:942
qint64 write(const char *data, qint64 len)
Writes at most maxSize bytes of data from data to the device.
Definition: qiodevice.cpp:1342
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66
virtual bool seek(qint64 pos)
For random-access devices, this function sets the current position to pos, returning true on success...
Definition: qiodevice.cpp:659
The Text item allows you to add formatted text to a scene.
#define forever
This macro is provided for convenience for writing infinite loops.
Definition: qglobal.h:2452

◆ write() [2/3]

qint64 QIODevice::write ( const char *  data)

Writes data from a zero-terminated string of 8-bit characters to the device.

Since
4.5

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Returns the number of bytes that were actually written, or -1 if an error occurred. This is equivalent to

...
QIODevice::write(data, qstrlen(data));
...
See also
read() writeData()

Definition at line 1435 of file qiodevice.cpp.

1436 {
1437  return write(data, qstrlen(data));
1438 }
static const char * data(const QByteArray &arr)
uint qstrlen(const char *str)
Definition: qbytearray.h:79
qint64 write(const char *data, qint64 len)
Writes at most maxSize bytes of data from data to the device.
Definition: qiodevice.cpp:1342

◆ write() [3/3]

qint64 QIODevice::write ( const QByteArray byteArray)
inline

Writes the content of byteArray to the device.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Returns the number of bytes that were actually written, or -1 if an error occurred.

See also
read() writeData()

Definition at line 126 of file qiodevice.h.

127  { return write(data.constData(), data.size()); }
static const char * data(const QByteArray &arr)
qint64 write(const char *data, qint64 len)
Writes at most maxSize bytes of data from data to the device.
Definition: qiodevice.cpp:1342

◆ writeData()

qint64 QIODevice::writeData ( const char *  data,
qint64  maxSize 
)
protectedpure virtual

Writes up to maxSize 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.

When reimplementing this function it is important that this function writes all the data available before returning. This is required in order for QDataStream to be able to operate on the class. QDataStream assumes all the information was written and therefore does not retry writing if there was a problem.

See also
read() write()

Implemented in QtMultimediaInternal::MacInputDevice, MacOutputDevice, QAuthDevice, QProcess, QFile, QAbstractSocket, QSslSocket, QUnixSocket, QByteDeviceWrappingIoDevice, QNetworkReply, OutputPrivate, InputPrivate, QHttpMultiPartIODevice, InputPrivate, OutputPrivate, QLocalSocket, QBuffer, and QOstDevice.

Referenced by QUnixSocket::read(), and write().


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