QIODevice Class Reference

#include <qiodevice.h>

Inheritance diagram for QIODevice:

Inheritance graph
[legend]
Collaboration diagram for QIODevice:

Collaboration graph
[legend]
List of all members.

Detailed Description

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

QIODevice provides both a common implementation and an abstract interface for devices that support reading and writing of blocks of data, such as QFile, QBuffer and QTcpSocket. QIODevice is abstract and can not be instantiated, but 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.

Random-access devices support seeking to arbitrary positions using seek(). The current position in the file is available by calling pos(). QFile and QBuffer are examples of random-access devices.

Sequential devices don't support seeking to arbitrary positions. The data must be read in one pass. The functions pos() and size() don't work for sequential devices. QTcpSocket and QProcess are examples of sequential devices.

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

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

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

waitForReadyRead() - This function suspends operation in the calling thread until new data is available for reading.

waitForBytesWritten() - This function suspends operation in the calling thread until one payload of data has been written to the device.

waitFor....() - Subclasses of QIODevice implement blocking functions for device-specific operations. For example, QProcess has a function called waitForStarted() which suspends operation in the calling thread until the process has started.

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

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

        gzip.write("uncompressed data");

        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 45 of file qiodevice.h.

Public Types

enum  OpenModeFlag

Signals

void readyRead ()
void bytesWritten (qint64 bytes)
void aboutToClose ()

Public Member Functions

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

Protected Member Functions

 QIODevice (QIODevicePrivate &dd, QObject *parent=0)
virtual qint64 readData (char *data, qint64 maxlen)=0
virtual qint64 readLineData (char *data, qint64 maxlen)
virtual qint64 writeData (const char *data, qint64 len)=0
void setOpenMode (OpenMode openMode)
void setErrorString (const QString &errorString)


Member Enumeration Documentation

enum QIODevice::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 QIODevice::Unbuffered and QIODevice::Truncate, might be meaningless for some subclasses. (For example, access to a QBuffer is always unbuffered.)

Definition at line 54 of file qiodevice.h.

00054                       {
00055         NotOpen = 0x0000,
00056         ReadOnly = 0x0001,
00057         WriteOnly = 0x0002,
00058         ReadWrite = ReadOnly | WriteOnly,
00059         Append = 0x0004,
00060         Truncate = 0x0008,
00061         Text = 0x0010,
00062         Unbuffered = 0x0020
00063     };


Constructor & Destructor Documentation

QIODevice::QIODevice (  ) 

Constructs a QIODevice object.

Definition at line 329 of file qiodevice.cpp.

References QFile::fileName(), and printf.

00330     : QObject(*new QIODevicePrivate, 0)
00331 {
00332 #if defined QIODEVICE_DEBUG
00333     QFile *file = qobject_cast<QFile *>(this);
00334     printf("%p QIODevice::QIODevice(\"%s\") %s\n", this, className(),
00335            qPrintable(file ? file->fileName() : QString()));
00336 #endif
00337 }

Here is the call graph for this function:

QIODevice::QIODevice ( QObject parent  )  [explicit]

Constructs a QIODevice object with the given parent.

Definition at line 343 of file qiodevice.cpp.

References QObject::parent(), and printf.

00344     : QObject(*new QIODevicePrivate, parent)
00345 {
00346 #if defined QIODEVICE_DEBUG
00347     printf("%p QIODevice::QIODevice(%p \"%s\")\n", this, parent, className());
00348 #endif
00349 }

Here is the call graph for this function:

QIODevice::~QIODevice (  )  [virtual]

Destructs the QIODevice object.

Definition at line 363 of file qiodevice.cpp.

References printf.

00364 {
00365 #if defined QIODEVICE_DEBUG
00366     printf("%p QIODevice::~QIODevice()\n", this);
00367 #endif
00368 }

QIODevice::QIODevice ( QIODevicePrivate dd,
QObject parent = 0 
) [protected]

Definition at line 353 of file qiodevice.cpp.

00354     : QObject(dd, parent)
00355 {
00356 }


Member Function Documentation

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 399 of file qiodevice.cpp.

Referenced by isReadable(), isWritable(), and seek().

00400 {
00401     return d_func()->openMode;
00402 }

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.

See also:
open(), setOpenMode()

Definition at line 426 of file qiodevice.cpp.

References d, and Text.

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

00427 {
00428     Q_D(QIODevice);
00429     if (enabled)
00430         d->openMode |= Text;
00431     else
00432         d->openMode &= ~Text;
00433 }

bool QIODevice::isTextModeEnabled (  )  const

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

See also:
setTextModeEnabled()

Definition at line 440 of file qiodevice.cpp.

References Text.

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

00441 {
00442     return d_func()->openMode & Text;
00443 }

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 453 of file qiodevice.cpp.

References NotOpen.

Referenced by QAbstractSocket::atEnd(), QProcess::atEnd(), QFile::atEnd(), QBuffer::canReadLine(), QMngPlugin::capabilities(), QJpegPlugin::capabilities(), QSvgPlugin::capabilities(), QPicturePrivate::checkFormat(), QFile::close(), Q3Socket::close(), QStringBuffer::close(), Q3SocketDevice::close(), Q3Http::close(), QHttpPrivate::closeConn(), QTemporaryFile::createLocalFile(), QXmlInputSource::fetchData(), QTemporaryFile::fileName(), Q3Socket::flush(), Q3Socket::getch(), QFile::handle(), QImageReaderPrivate::initHandler(), Q3Socket::open(), QStringBuffer::open(), QFile::open(), Q3SocketDevice::open(), QPictureIO::read(), QStringBuffer::readData(), Q3Socket::readData(), Q3SocketDevice::readData(), PreprocessorCache::readFile(), PreprocessorController::readFile(), QFile::rename(), QFile::resize(), QFile::seek(), QBuffer::setBuffer(), QBuffer::setData(), QFile::setFileName(), QTemporaryFile::setFileTemplate(), Q3HttpNormalRequest::start(), QHttpNormalRequest::start(), QConfFileSettingsPrivate::syncConfFile(), Q3Socket::ungetch(), QPictureIO::write(), Q3SocketDevice::writeBlock(), Q3Socket::writeData(), QStringBuffer::writeData(), Q3SocketDevice::writeData(), and FileWriter::writeFile().

00454 {
00455     return d_func()->openMode != NotOpen;
00456 }

bool QIODevice::isReadable (  )  const

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

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

See also:
openMode() OpenMode

Definition at line 467 of file qiodevice.cpp.

References openMode(), and ReadOnly.

Referenced by QJpegPlugin::capabilities(), QMngPlugin::capabilities(), QGifPlugin::capabilities(), QSvgPlugin::capabilities(), QBuffer::open(), QStringBuffer::readData(), Q3SocketDevice::readData(), and QConfFileSettingsPrivate::syncConfFile().

00468 {
00469     return (openMode() & ReadOnly) != 0;
00470 }

Here is the call graph for this function:

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 481 of file qiodevice.cpp.

References openMode(), and WriteOnly.

Referenced by QJpegPlugin::capabilities(), QBuffer::open(), QConfFileSettingsPrivate::syncConfFile(), write_xpm_image(), Q3SocketDevice::writeBlock(), QStringBuffer::writeData(), and Q3SocketDevice::writeData().

00482 {
00483     return (openMode() & WriteOnly) != 0;
00484 }

Here is the call graph for this function:

bool QIODevice::isSequential (  )  const [virtual]

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

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

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

See also:
bytesAvailable()

Definition at line 388 of file qiodevice.cpp.

Referenced by QXbmHandler::canRead(), createReadHandler(), QTextStreamPrivate::fillReadBuffer(), QMoviePrivate::infoForFrame(), QFtp::put(), qt_term_source(), and QDataStream::skipRawData().

00389 {
00390     return false;
00391 }

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

Opens the device and sets its OpenMode to mode. Returns true if successful; otherwise returns false.

See also:
openMode() OpenMode

Definition at line 492 of file qiodevice.cpp.

References Append, d, printf, size(), and QIODevicePrivate::Unset.

Referenced by QXmlInputSource::fetchData(), QImageReaderPrivate::initHandler(), Q3SocketDevice::open(), QPdfBaseEnginePrivate::openPrintDevice(), Q3TextStream::Q3TextStream(), Q3HttpNormalRequest::start(), and QHttpNormalRequest::start().

00493 {
00494     Q_D(QIODevice);
00495     d->openMode = mode;
00496     d->pos = (mode & Append) ? size() : qint64(0);
00497     d_func()->accessMode = QIODevicePrivate::Unset;
00498 #if defined QIODEVICE_DEBUG
00499     printf("%p QIODevice::open(0x%x)\n", this, quint32(mode));
00500 #endif
00501     return true;
00502 }

Here is the call graph for this function:

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

Definition at line 510 of file qiodevice.cpp.

References aboutToClose(), d, emit, NotOpen, and printf.

Referenced by QFile::close(), QBuffer::close(), QStringBuffer::close(), QAbstractSocket::close(), Q3SocketDevice::close(), QPdfBaseEnginePrivate::closePrintDevice(), and QAbstractSocket::disconnectFromHostImplementation().

00511 {
00512     Q_D(QIODevice);
00513     if (d->openMode == NotOpen)
00514         return;
00515 
00516 #if defined QIODEVICE_DEBUG
00517     printf("%p QIODevice::close()\n", this);
00518 #endif
00519 
00520 #ifndef QT_NO_QOBJECT
00521     emit aboutToClose();
00522 #endif
00523     d->openMode = NotOpen;
00524     d->errorString.clear();
00525     d->pos = 0;
00526     d->buffer.clear();
00527 }

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

Definition at line 542 of file qiodevice.cpp.

References d, and printf.

Referenced by QHttpPrivate::_q_slotBytesWritten(), QXbmHandler::canRead(), QTextStreamPrivate::consume(), qdesigner_internal::Connection::contains(), createReadHandler(), QJpegHandler::option(), QBuffer::pos(), QFile::pos(), QMovie::QMovie(), qt_term_source(), QStringBuffer::readData(), QMoviePrivate::reset(), qdesigner_internal::Connection::setSource(), qdesigner_internal::Connection::setTarget(), QDataStream::skipRawData(), Translator::squeeze(), and QStringBuffer::writeData().

00543 {
00544     Q_D(const QIODevice);
00545 #if defined QIODEVICE_DEBUG
00546     printf("%p QIODevice::pos() == %d\n", this, int(d->pos));
00547 #endif
00548     return d->pos;
00549 }

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

Definition at line 560 of file qiodevice.cpp.

References bytesAvailable().

Referenced by QHttpPrivate::_q_slotBytesWritten(), QHttpPrivate::_q_slotConnected(), atEnd(), bytesAvailable(), qdesigner_internal::Connection::labelRect(), open(), Q3Ftp::put(), QFtp::put(), readAll(), readLine(), PeerWireClient::sendPieceList(), QDataStream::skipRawData(), Q3Http::slotBytesWritten(), Q3Http::slotConnected(), Q3HttpNormalRequest::start(), and qdesigner_internal::Connection::updatePixmap().

00561 {
00562     return d_func()->isSequential() ?  bytesAvailable() : qint64(0);
00563 }

Here is the call graph for this function:

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

Definition at line 577 of file qiodevice.cpp.

References d, NotOpen, openMode(), printf, and qWarning().

Referenced by QXbmHandler::canRead(), QStringBuffer::close(), createReadHandler(), QMoviePrivate::infoForFrame(), QStringBuffer::open(), QJpegHandler::option(), qt_term_source(), read(), readLine(), reset(), QBuffer::seek(), QFile::seek(), Server::sendFortune(), QDataStream::skipRawData(), and write().

00578 {
00579     if (d_func()->openMode == NotOpen) {
00580         qWarning("QIODevice::seek: The device is not open");
00581         return false;
00582     }
00583     if (pos < 0) {
00584         qWarning("QIODevice::seek: Invalid pos: %d", int(pos));
00585         return false;
00586     }
00587 
00588     Q_D(QIODevice);
00589 #if defined QIODEVICE_DEBUG
00590     printf("%p QIODevice::seek(%d), before: d->pos = %d, d->buffer.size() = %d\n",
00591            this, int(pos), int(d->pos), d->buffer.size());
00592 #endif
00593 
00594     qint64 offset = pos - d->pos;
00595     if (!d->isSequential()) {
00596         d->pos = pos;
00597         d->devicePos = pos;
00598     }
00599 
00600     if (offset > 0 && !d->buffer.isEmpty()) {
00601         // When seeking forwards, we need to pop bytes off the front of the
00602         // buffer.
00603         do {
00604             int bytesToSkip = int(qMin<qint64>(offset, INT_MAX));
00605             d->buffer.skip(bytesToSkip);
00606             offset -= bytesToSkip;
00607         } while (offset > 0);
00608     } else if (offset < 0) {
00609         // When seeking backwards, an operation that is only allowed for
00610         // random-access devices, the buffer is cleared. The next read
00611         // operation will then refill the buffer. We can optimize this, if we
00612         // find that seeking backwards becomes a significant performance hit.
00613         d->buffer.clear();
00614     }
00615 #if defined QIODEVICE_DEBUG
00616     printf("%p \tafter: d->pos == %d, d->buffer.size() == %d\n", this, int(d->pos),
00617            d->buffer.size());
00618 #endif
00619     return true;
00620 }

Here is the call graph for this function:

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

Definition at line 634 of file qiodevice.cpp.

References bytesAvailable(), d, NotOpen, printf, and size().

Referenced by QHttpPrivate::_q_slotBytesWritten(), QBuffer::atEnd(), QDataStream::atEnd(), Q3TextStream::atEnd(), QAbstractSocket::atEnd(), QProcess::atEnd(), QFile::atEnd(), QTextStreamPrivate::fillReadBuffer(), MocParser::loadIntData(), MocParser::loadStringData(), MocParser::parse(), ProReader::read(), QTextStreamPrivate::scan(), Q3Http::slotBytesWritten(), Q3TextStream::ts_getbuf(), and Q3TextStream::ts_getline().

00635 {
00636     Q_D(const QIODevice);
00637 #if defined QIODEVICE_DEBUG
00638     printf("%p QIODevice::atEnd() returns %s, d->openMode == %d, d->pos == %d\n", this, (d->openMode == NotOpen || d->pos == size()) ? "true" : "false",
00639            int(d->openMode), int(d->pos));
00640 #endif
00641     return d->openMode == NotOpen || (d->buffer.isEmpty() && bytesAvailable() == 0);
00642 }

Here is the call graph for this function:

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

Definition at line 655 of file qiodevice.cpp.

References printf, and seek().

Referenced by SaveFormAsTemplate::accept().

00656 {
00657 #if defined QIODEVICE_DEBUG
00658     printf("%p QIODevice::reset()\n", this);
00659 #endif
00660     return seek(0);
00661 }

Here is the call graph for this function:

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

Definition at line 680 of file qiodevice.cpp.

References d, qMax(), and size().

Referenced by atEnd(), QFile::atEnd(), QAbstractSocket::bytesAvailable(), QProcess::bytesAvailable(), Q3SocketDevice::bytesAvailable(), Q3Socket::bytesAvailable(), read(), readAll(), and size().

00681 {
00682     Q_D(const QIODevice);
00683     if (!d->isSequential())
00684         return qMax(size() - d->pos, qint64(0));
00685     return d->buffer.size();
00686 }

Here is the call graph for this function:

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

Definition at line 695 of file qiodevice.cpp.

00696 {
00697     return qint64(0);
00698 }

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.

See also:
readData() readLine() write()

Definition at line 710 of file qiodevice.cpp.

References c, CHECK_MAXLEN, CHECK_OPEN, CHECK_READABLE, d, int, printf, qMax(), readData(), seek(), Text, and Unbuffered.

Referenced by QHttpPrivate::_q_slotBytesWritten(), QHttpPrivate::_q_slotReadyRead(), QGLContext::bindTexture(), QSocks5PasswordAuthenticator::continueAuthenticate(), QFile::copy(), QTemporaryFile::createLocalFile(), QTextStreamPrivate::fillReadBuffer(), QGifHandler::imageIsComing(), iod_read_fn(), QTranslator::load(), MainWindow::loadLayout(), QDataStream::operator>>(), QSocks5SocketEnginePrivate::parseAuthenticationMethodReply(), peek(), Connection::processData(), PeerWireClient::processIncomingData(), Connection::processReadyRead(), qt_fill_input_buffer(), QFtpDTP::read(), QGifHandler::read(), read(), read_pbm_body(), read_pbm_header(), readAll(), Q3SocketDevice::readBlock(), QDataStream::readBytes(), Q3SocketDevice::readData(), QFile::readData(), Connection::readDataIntoBuffer(), PeerWireClient::readFromSocket(), QDataStream::readRawData(), QDynamicResourceRoot::registerSelf(), QFile::rename(), QDataStream::skipRawData(), QFtpDTP::socketReadyRead(), and ungetChar().

00711 {
00712     Q_D(QIODevice);
00713     CHECK_OPEN(read, qint64(-1));
00714     CHECK_READABLE(read, qint64(-1));
00715     CHECK_MAXLEN(read, qint64(-1));
00716 
00717 #if defined QIODEVICE_DEBUG
00718     printf("%p QIODevice::read(%p, %d), d->pos = %d, d->buffer.size() = %d\n",
00719            this, data, int(maxSize), int(d->pos), int(d->buffer.size()));
00720 #endif
00721     const bool sequential = d->isSequential();
00722 
00723     // Short circuit for getChar()
00724     if (maxSize == 1) {
00725         int chint = d->buffer.getChar();
00726         if (chint != -1) {
00727             char c = char(uchar(chint));
00728             if (c == '\r' && (d->openMode & Text)) {
00729                 d->buffer.ungetChar(c);
00730             } else {
00731                 if (data)
00732                     *data = c;
00733                 if (!sequential)
00734                     ++d->pos;
00735 #if defined QIODEVICE_DEBUG
00736                 printf("%p \tread 0x%hhx (%c) returning 1 (shortcut)\n", this,
00737                        int(c), isprint(c) ? c : '?');
00738 #endif
00739                 return qint64(1);
00740             }
00741         }
00742     }
00743 
00744     qint64 readSoFar = 0;
00745     bool moreToRead = true;
00746     do {
00747         int lastReadChunkSize = 0;
00748 
00749         // Try reading from the buffer.
00750         if (!d->buffer.isEmpty()) {
00751             lastReadChunkSize = d->buffer.read(data + readSoFar, maxSize - readSoFar);
00752             readSoFar += lastReadChunkSize;
00753             if (!sequential)
00754                 d->pos += lastReadChunkSize;
00755 #if defined QIODEVICE_DEBUG
00756             printf("%p \treading %d bytes from buffer into position %d\n", this, lastReadChunkSize,
00757                    int(readSoFar) - lastReadChunkSize);
00758 #endif
00759         } else if ((d->openMode & Unbuffered) == 0 && maxSize < QIODEVICE_BUFFERSIZE) {
00760             // In buffered mode, we try to fill up the QIODevice buffer before
00761             // we do anything else.
00762             int bytesToBuffer = qMax(maxSize - readSoFar, QIODEVICE_BUFFERSIZE);
00763             char *writePointer = d->buffer.reserve(bytesToBuffer);
00764 
00765             // Make sure the device is positioned correctly.
00766             if (d->pos != d->devicePos && !sequential && !seek(d->pos))
00767                 return qint64(-1);
00768             qint64 readFromDevice = readData(writePointer, bytesToBuffer);
00769             d->buffer.chop(bytesToBuffer - (readFromDevice < 0 ? 0 : int(readFromDevice)));
00770 
00771             if (readFromDevice > 0) {
00772                 if (!sequential)
00773                     d->devicePos += readFromDevice;
00774 #if defined QIODEVICE_DEBUG
00775                 printf("%p \treading %d from device into buffer\n", this, int(readFromDevice));
00776 #endif
00777 
00778                 if (readFromDevice < bytesToBuffer)
00779                     d->buffer.truncate(readFromDevice < 0 ? 0 : int(readFromDevice));
00780                 if (!d->buffer.isEmpty()) {
00781                     lastReadChunkSize = d->buffer.read(data + readSoFar, maxSize - readSoFar);
00782                     readSoFar += lastReadChunkSize;
00783                     if (!sequential)
00784                         d->pos += lastReadChunkSize;
00785 #if defined QIODEVICE_DEBUG
00786                     printf("%p \treading %d bytes from buffer at position %d\n", this,
00787                            lastReadChunkSize, int(readSoFar));
00788 #endif
00789                 }
00790             }
00791         }
00792 
00793         // If we need more, try reading from the device.
00794         if (readSoFar < maxSize) {
00795             // Make sure the device is positioned correctly.
00796             if (d->pos != d->devicePos && !sequential && !seek(d->pos))
00797                 return qint64(-1);
00798             qint64 readFromDevice = readData(data + readSoFar, maxSize - readSoFar);
00799 #if defined QIODEVICE_DEBUG
00800             printf("%p \treading %d bytes from device\n", this, int(readFromDevice));
00801 #endif
00802             if (readFromDevice <= 0) {
00803                 moreToRead = false;
00804             } else {
00805                 // see if we read as much data as we asked for
00806                 if (readFromDevice < maxSize - readSoFar)
00807                     moreToRead = false;
00808 
00809                 lastReadChunkSize += int(readFromDevice);
00810                 readSoFar += readFromDevice;
00811                 if (!sequential) {
00812                     d->pos += readFromDevice;
00813                     d->devicePos += readFromDevice;
00814                 }
00815             }
00816         } else {
00817             moreToRead = false;
00818         }
00819 
00820         if (readSoFar && d->openMode & Text) {
00821             char *readPtr = data + readSoFar - lastReadChunkSize;
00822             const char *endPtr = data + readSoFar;
00823 
00824             if (readPtr < endPtr) {
00825                 // optimization to avoid initial self-assignment
00826                 while (*readPtr != '\r') {
00827                     if (++readPtr == endPtr)
00828                         return readSoFar;
00829                 }
00830 
00831                 char *writePtr = readPtr;
00832 
00833                 while (readPtr < endPtr) {
00834                     char ch = *readPtr++;
00835                     if (ch != '\r')
00836                         *writePtr++ = ch;
00837                     else
00838                         --readSoFar;
00839                 }
00840 
00841                 // Make sure we get more data if there is room for more. This
00842                 // is very important for when someone seeks to the start of a
00843                 // '\r\n' and reads one character - they should get the '\n'.
00844                 moreToRead = (readPtr != writePtr);
00845             }
00846         }
00847     } while (moreToRead);
00848 
00849 #if defined QIODEVICE_DEBUG
00850     printf("%p \treturning %d, d->pos == %d, d->buffer.size() == %d\n", this,
00851            int(readSoFar), int(d->pos), d->buffer.size());
00852     debugBinaryString(data, readSoFar);
00853 #endif
00854     return readSoFar;
00855 }

Here is the call graph for this function:

QByteArray QIODevice::read ( qint64  maxSize  ) 

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Reads at most maxSize bytes from the device, and returns the data read as a QByteArray.

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

Definition at line 867 of file qiodevice.cpp.

References buffer, bytesAvailable(), CHECK_MAXLEN, d, printf, qMin(), and read().

00868 {
00869     Q_D(QIODevice);
00870     CHECK_MAXLEN(read, QByteArray());
00871     QByteArray tmp;
00872     qint64 readSoFar = 0;
00873     char buffer[4096];
00874 #if defined QIODEVICE_DEBUG
00875     printf("%p QIODevice::read(%d), d->pos = %d, d->buffer.size() = %d\n",
00876            this, int(maxSize), int(d->pos), int(d->buffer.size()));
00877 #else
00878     Q_UNUSED(d);
00879 #endif
00880 
00881     do {
00882         qint64 bytesToRead = qMin(int(maxSize - readSoFar), int(sizeof(buffer)));
00883         qint64 readBytes = read(buffer, bytesToRead);
00884         if (readBytes <= 0)
00885             break;
00886         tmp += QByteArray(buffer, (int) readBytes);
00887         readSoFar += readBytes;
00888     } while (readSoFar < maxSize && bytesAvailable() > 0);
00889 
00890     return tmp;
00891 }

Here is the call graph for this function:

QByteArray QIODevice::readAll (  ) 

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Reads all available data from the device, and returns it as a QByteArray.

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

Definition at line 903 of file qiodevice.cpp.

References bytesAvailable(), QByteArray::chop(), d, QByteArray::data(), printf, read(), QByteArray::resize(), QByteArray::size(), and size().

Referenced by QHttpPrivate::_q_slotReadyRead(), QFontDatabase::addApplicationFont(), qdesigner_internal::QDesignerResource::create(), QXmlInputSource::fetchData(), QFreetypeFace::getFace(), TextEdit::load(), QPicture::load(), ArthurFrame::loadDescription(), MainWindow::loadLayout(), QTextBrowser::loadResource(), main(), MainWindow::on_actionAboutApplication_triggered(), FindFileDialog::openFile(), ProjectPorter::portProFile(), Preprocessor::preprocess(), Preprocessor::preprocessed(), PreprocessorController::PreprocessorController(), qt_unix_query(), Q3FtpDTP::readAll(), QFtpDTP::readAll(), QProcess::readAllStandardError(), QProcess::readAllStandardOutput(), PreprocessorCache::readFile(), PreprocessorController::readFile(), readInput(), qdesigner_internal::BrushManagerProxy::setBrushManager(), TorrentClient::setTorrent(), AddTorrentDialog::setTorrent(), TrPreviewTool::showAboutBox(), ArthurFrame::showSource(), Q3Http::slotReadyRead(), QFtpDTP::socketConnectionClosed(), QFtpDTP::socketReadyRead(), QConfFileSettingsPrivate::syncConfFile(), QSocks5Authenticator::unSeal(), and Dialog::updateServerProgress().

00904 {
00905     Q_D(QIODevice);
00906 #if defined QIODEVICE_DEBUG
00907     printf("%p QIODevice::readAll(), d->pos = %d, d->buffer.size() = %d\n",
00908            this, int(d->pos), int(d->buffer.size()));
00909 #endif
00910 
00911     QByteArray tmp;
00912     if (d->isSequential() || size() == 0) {
00913         // Read it in chunks, bytesAvailable() is unreliable for sequential
00914         // devices.
00915         const int chunkSize = 4096;
00916         qint64 totalRead = 0;
00917         forever {
00918             tmp.resize(tmp.size() + chunkSize);
00919             qint64 readBytes = read(tmp.data() + totalRead, chunkSize);
00920             tmp.chop(chunkSize - (readBytes < 0 ? 0 : readBytes));
00921             if (readBytes <= 0)
00922                 return tmp;
00923             totalRead += readBytes;
00924         }
00925     } else {
00926         // Read it all in one go.
00927         tmp.resize(int(bytesAvailable()));
00928         qint64 readBytes = read(tmp.data(), tmp.size());
00929         tmp.resize(readBytes < 0 ? 0 : int(readBytes));
00930     }
00931     return tmp;
00932 }

Here is the call graph for this function:

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 an error occurred, -1 is returned.

A terminating '' 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
            }
        }

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

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 975 of file qiodevice.cpp.

References d, int, printf, qWarning(), readLineData(), seek(), size(), and Text.

Referenced by QHttpPrivate::_q_slotReadyRead(), DocuParser::createParser(), QTextStreamPrivate::fillReadBuffer(), fontFile(), fontPath(), getLprPrinters(), QCleanlooksStylePrivate::lookupIconTheme(), main(), MainWindow::modelFromFile(), parseEtcLpPrinters(), parseNsswitchConf(), parsePrintcap(), parsePrintersConf(), qt_read_xpm_image_or_array(), ProReader::read(), read_xbm_body(), read_xbm_header(), AssistantSocket::readClient(), QDesignerServer::readFromClient(), QDesignerClient::readFromSocket(), readLine(), MocParser::readLine(), QFtpPI::readyRead(), Q3FtpPI::readyRead(), Q3Http::slotReadyRead(), QFtpDTP::socketReadyRead(), Q3FtpDTP::socketReadyRead(), Ping::start(), and Q3TextStream::ts_getline().

00976 {
00977     Q_D(QIODevice);
00978     if (maxSize < 2) {
00979         qWarning("QIODevice::readLine: Called with maxSize < 2");
00980         return qint64(-1);
00981     }
00982 
00983 #if defined QIODEVICE_DEBUG
00984     printf("%p QIODevice::readLine(%p, %d), d->pos = %d, d->buffer.size() = %d\n",
00985            this, data, int(maxSize), int(d->pos), int(d->buffer.size()));
00986 #endif
00987 
00988     // Leave room for a '\0'
00989     --maxSize;
00990 
00991     const bool sequential = d->isSequential();
00992 
00993     qint64 readSoFar = 0;
00994     if (!d->buffer.isEmpty()) {
00995         readSoFar = d->buffer.readLine(data, maxSize);
00996         if (!sequential)
00997             d->pos += readSoFar;
00998 #if defined QIODEVICE_DEBUG
00999         printf("%p \tread from buffer: %d bytes, last character read: %hhx\n", this,
01000                int(readSoFar), data[int(readSoFar) - 1]);
01001         if (readSoFar)
01002             debugBinaryString(data, int(readSoFar));
01003 #endif
01004         if (readSoFar && data[readSoFar - 1] == '\n') {
01005             data[readSoFar] = '\0';
01006             return readSoFar;
01007         }
01008     }
01009 
01010     if (d->pos != d->devicePos && !sequential && !seek(d->pos))
01011         return qint64(-1);
01012     d->baseReadLineDataCalled = false;
01013     qint64 readBytes = readLineData(data + readSoFar, maxSize - readSoFar);
01014 #if defined QIODEVICE_DEBUG
01015     printf("%p \tread from readLineData: %d bytes, readSoFar = %d bytes\n", this,
01016            int(readBytes), int(readSoFar));
01017     if (readBytes > 0) {
01018         debugBinaryString(data, int(readSoFar + readBytes));
01019     }
01020 #endif
01021     if (readBytes <= 0) {
01022         data[readSoFar] = '\0';
01023         return readSoFar ? readSoFar : -1;
01024     }
01025     readSoFar += readBytes;
01026     if (!d->baseReadLineDataCalled && !sequential) {
01027         d->pos += readBytes;
01028         // If the base implementation was not called, then we must
01029         // assume the device position is invalid and force a seek.
01030         d->devicePos = qint64(-1);
01031     }
01032     data[readSoFar] = '\0';
01033 
01034     if (d->openMode & Text) {
01035         if (readSoFar > 1 && data[readSoFar - 1] == '\n' && data[readSoFar - 2] == '\r') {
01036             data[readSoFar - 2] = '\n';
01037             data[readSoFar - 1] = '\0';
01038             --readSoFar;
01039         }
01040     }
01041 
01042 #if defined QIODEVICE_DEBUG
01043     printf("%p \treturning %d, d->pos = %d, d->buffer.size() = %d, size() = %d\n",
01044            this, int(readSoFar), int(d->pos), d->buffer.size(), int(size()));
01045     debugBinaryString(data, int(readSoFar));
01046 #endif
01047     return readSoFar;
01048 }

Here is the call graph for this function:

QByteArray QIODevice::readLine ( qint64  maxSize = 0  ) 

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Reads a line from the device, but no more than maxSize characters, and returns the result as a QByteArray.

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

Definition at line 1060 of file qiodevice.cpp.

References QByteArray::at(), CHECK_MAXLEN, d, QByteArray::data(), printf, qMin(), readLine(), QByteArray::resize(), and QByteArray::size().

01061 {
01062     Q_D(QIODevice);
01063     CHECK_MAXLEN(readLine, QByteArray());
01064     QByteArray tmp;
01065     const int BufferGrowth = 4096;
01066     qint64 readSoFar = 0;
01067     qint64 readBytes = 0;
01068 
01069 #if defined QIODEVICE_DEBUG
01070     printf("%p QIODevice::readLine(%d), d->pos = %d, d->buffer.size() = %d\n",
01071            this, int(maxSize), int(d->pos), int(d->buffer.size()));
01072 #else
01073     Q_UNUSED(d);
01074 #endif
01075 
01076     do {
01077         if (maxSize != 0)
01078             tmp.resize(int(readSoFar + qMin(int(maxSize), BufferGrowth)));
01079         else
01080             tmp.resize(int(readSoFar + BufferGrowth));
01081         readBytes = readLine(tmp.data() + readSoFar, tmp.size() - readSoFar);
01082         if (readBytes <= 0)
01083             break;
01084 
01085         readSoFar += readBytes;
01086     } while ((!maxSize || readSoFar < maxSize) &&
01087              readSoFar + 1 == tmp.size() &&   // +1 due to the ending null
01088              tmp.at(readSoFar - 1) != '\n');
01089 
01090     tmp.resize(int(readSoFar));
01091     return tmp;
01092 }

Here is the call graph for this function:

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 size of the QIODevice's buffer. Example:

        bool CustomDevice::canReadLine() const
        {
            return buffer.contains('\n') || QIODevice::canReadLine();
        }

See also:
readyRead(), readLine()

Definition at line 1151 of file qiodevice.cpp.

Referenced by QAbstractSocket::canReadLine(), QProcess::canReadLine(), and QBuffer::canReadLine().

01152 {
01153     return d_func()->buffer.canReadLine();
01154 }

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 1172 of file qiodevice.cpp.

References CHECK_MAXLEN, CHECK_OPEN, CHECK_WRITABLE, d, seek(), Text, and writeData().

Referenced by QSocks5SocketEnginePrivate::_q_controlSocketConnected(), QHttpPrivate::_q_slotBytesWritten(), QHttpPrivate::_q_slotConnected(), QHttpPrivate::_q_slotReadyRead(), QFtpPI::abort(), SaveFormAsTemplate::accept(), QSocks5PasswordAuthenticator::beginAuthenticate(), PeerWireClient::cancelRequest(), PeerWireClient::chokePeer(), QFile::copy(), qdesigner_internal::QDesignerResource::copy(), QTemporaryFile::createLocalFile(), defaultMacros(), QPdfEnginePrivate::embedFont(), QPSPrintEnginePrivate::emitHeader(), QPSPrintEnginePrivate::emitPages(), Q3Socket::flush(), QTextStreamPrivate::flushWriteBuffer(), main(), QDataStream::operator<<(), Connection::processData(), qpiw_write_fn(), qt_empty_output_buffer(), qt_get_net_supported(), qt_get_net_virtual_roots(), qt_term_destination(), registerFont(), QFile::rename(), PeerWireClient::requestBlock(), QPicture::save(), QAbstractFormBuilder::save(), MainWindow::saveLayout(), Server::sendFortune(), Connection::sendGreetingMessage(), PeerWireClient::sendHandShake(), PeerWireClient::sendInterested(), PeerWireClient::sendKeepAlive(), Connection::sendMessage(), PeerWireClient::sendNotInterested(), QDesignerServer::sendOpenRequest(), PeerWireClient::sendPieceList(), PeerWireClient::sendPieceNotification(), Connection::sendPing(), QSocks5SocketEnginePrivate::sendRequestMethod(), QFtpPI::startNextCmd(), Dialog::startTransfer(), PeerWireClient::unchokePeer(), ungetChar(), Dialog::updateClientProgress(), QAnimationWriterMNG::write(), write_pbm_image(), write_xbm_image(), writeAdaptor(), Q3SocketDevice::writeBlock(), Q3TextStream::writeBlock(), Q3SocketDevice::writeData(), QFtpDTP::writeData(), FileWriter::writeFile(), QConfFileSettingsPrivate::writeIniFile(), QAnimationWriterMNG::writeMHDR(), QDesignerActions::writeOutForm(), writeProxy(), QDataStream::writeRawData(), and PeerWireClient::writeToSocket().

01173 {
01174     Q_D(QIODevice);
01175     CHECK_OPEN(write, qint64(-1));
01176     CHECK_WRITABLE(write, qint64(-1));
01177     CHECK_MAXLEN(write, qint64(-1));
01178 
01179     const bool sequential = d->isSequential();
01180     // Make sure the device is positioned correctly.
01181     if (d->pos != d->devicePos && !sequential && !seek(d->pos))
01182         return qint64(-1);
01183 
01184 #ifdef Q_OS_WIN
01185     if (d->openMode & Text) {
01186         const char *endOfData = data + maxSize;
01187         const char *startOfBlock = data;
01188 
01189         qint64 writtenSoFar = 0;
01190 
01191         forever {
01192             const char *endOfBlock = startOfBlock;
01193             while (endOfBlock < endOfData && *endOfBlock != '\n')
01194                 ++endOfBlock;
01195 
01196             qint64 blockSize = endOfBlock - startOfBlock;
01197             if (blockSize > 0) {
01198                 qint64 ret = writeData(startOfBlock, blockSize);
01199                 if (ret <= 0) {
01200                     if (writtenSoFar && !sequential)
01201                         d->buffer.skip(writtenSoFar);
01202                     return writtenSoFar ? writtenSoFar : ret;
01203                 }
01204                 if (!sequential) {
01205                     d->pos += ret;
01206                     d->devicePos += ret;
01207                 }
01208                 writtenSoFar += ret;
01209             }
01210 
01211             if (endOfBlock == endOfData)
01212                 break;
01213 
01214             qint64 ret = writeData("\r\n", 2);
01215             if (ret <= 0) {
01216                 if (writtenSoFar && !sequential)
01217                     d->buffer.skip(writtenSoFar);
01218                 return writtenSoFar ? writtenSoFar : ret;
01219             }
01220             if (!sequential) {
01221                 d->pos += ret;
01222                 d->devicePos += ret;
01223             }
01224             ++writtenSoFar;
01225 
01226             startOfBlock = endOfBlock + 1;
01227         }
01228 
01229         if (writtenSoFar && !sequential)
01230             d->buffer.skip(writtenSoFar);
01231         return writtenSoFar;
01232     }
01233 #endif
01234 
01235     qint64 written = writeData(data, maxSize);
01236     if (written > 0) {
01237         if (!sequential) {
01238             d->pos += written;
01239             d->devicePos += written;
01240         }
01241         if (!d->buffer.isEmpty() && !sequential)
01242             d->buffer.skip(written);
01243     }
01244     return written;
01245 }

Here is the call graph for this function:

qint64 QIODevice::write ( const QByteArray byteArray  )  [inline]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Writes the content of byteArray to the device. Returns the number of bytes that were actually written, or -1 if an error occurred.

See also:
read() writeData()

Definition at line 104 of file qiodevice.h.

References data.

00105     { return write(data.constData(), data.size()); }

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

Since:
4.1
Reads at most maxSize bytes from the device into data, without side effects (i.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 1314 of file qiodevice.cpp.

References i, read(), and ungetChar().

Referenced by QJpegHandler::canRead(), QGifHandler::canRead(), QXpmHandler::canRead(), QPngHandler::canRead(), QMngHandler::canRead(), QSvgIOHandler::canRead(), QBmpHandler::canRead(), QPpmHandler::canRead(), and QTextStreamPrivate::fillReadBuffer().

01315 {
01316     qint64 readBytes = read(data, maxSize);
01317     int i = readBytes;
01318     while (i > 0)
01319         ungetChar(data[i-- - 1]);
01320     return readBytes;
01321 }

Here is the call graph for this function:

QByteArray QIODevice::peek ( qint64  maxSize  ) 

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. Peeks at most maxSize bytes from the device, returning the data peeked as a QByteArray.

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 1345 of file qiodevice.cpp.

References QByteArray::constData(), i, read(), QByteArray::size(), and ungetChar().

01346 {
01347     QByteArray result = read(maxSize);
01348     int i = result.size();
01349     const char *data = result.constData();
01350     while (i > 0)
01351         ungetChar(data[i-- - 1]);
01352     return result;
01353 }

Here is the call graph for this function:

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

Blocks until data is available for reading and the readyRead() signal has been emitted, or until msecs milliseconds have passed. If msecs is -1, this function will not time out.

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

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

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

Definition at line 1378 of file qiodevice.cpp.

01379 {
01380     Q_UNUSED(msecs);
01381     return false;
01382 }

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

Definition at line 1410 of file qiodevice.cpp.

01411 {
01412     Q_UNUSED(msecs);
01413     return false;
01414 }

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 1274 of file qiodevice.cpp.

References CHECK_OPEN, CHECK_READABLE, d, printf, Q_VOID, read(), and write().

Referenced by QSocks5SocketEnginePrivate::parseNewConnection(), QSocks5SocketEnginePrivate::parseRequestMethodReply(), peek(), qt_read_xpm_image_or_array(), and read_xpm_body().

01275 {
01276     Q_D(QIODevice);
01277     CHECK_OPEN(write, Q_VOID);
01278     CHECK_READABLE(read, Q_VOID);
01279 
01280 #if defined QIODEVICE_DEBUG
01281     printf("%p QIODevice::ungetChar(0x%hhx '%c')\n", this, c, isprint(c) ? c : '?');
01282 #endif
01283 
01284     d->buffer.ungetChar(c);
01285     if (!d->isSequential())
01286         --d->pos;
01287 }

Here is the call graph for this function:

bool QIODevice::putChar ( char  c  )  [inline]

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

See also:
write() getChar() ungetChar()

Definition at line 114 of file qiodevice.h.

Referenced by QDataStream::operator<<(), and MainWindow::saveLayout().

00114 { return write(&c, 1) == 1; }

bool QIODevice::getChar ( char *  c  )  [inline]

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 115 of file qiodevice.h.

Referenced by MainWindow::loadLayout(), QDataStream::operator>>(), read_xpm_body(), and readLineData().

00116     { char ch; bool result = read(&ch, 1) == 1; if (c) *c = ch; return result; }

QString QIODevice::errorString (  )  const

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

See also:
setErrorString()

Definition at line 1433 of file qiodevice.cpp.

References d.

Referenced by QSocks5SocketEnginePrivate::_q_controlSocketError(), SaveFormAsTemplate::accept(), QFile::close(), Client::displayError(), Dialog::displayError(), FtpWindow::downloadFile(), HttpWindow::downloadFile(), QFile::flush(), FileManager::generateFiles(), QSvgTinyDocument::load(), MainWindow::loadFile(), MdiChild::loadFile(), loadFile(), MainWindow::loadLayout(), main(), QFile::open(), openFile(), qt_unix_query(), QFile::readData(), QDesignerActions::readInForm(), QFile::rename(), FortuneThread::run(), MdiChild::saveFile(), MainWindow::saveFile(), MainWindow::saveLayout(), QFile::seek(), QAbstractSocket::waitForBytesWritten(), QAbstractSocket::waitForDisconnected(), QAbstractSocket::waitForReadyRead(), QFile::writeData(), and QDesignerActions::writeOutForm().

01434 {
01435     Q_D(const QIODevice);
01436     if (d->errorString.isEmpty()) {
01437 #ifdef QT_NO_QOBJECT
01438         return QT_TRANSLATE_NOOP(QIODevice, "Unknown error");
01439 #else
01440         return tr("Unknown error");
01441 #endif
01442     }
01443     return d->errorString;
01444 }

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

See also:
bytesWritten()

Referenced by AssistantSocket::AssistantSocket(), Connection::Connection(), and PeerWireClient::PeerWireClient().

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 PeerWireClient::PeerWireClient(), QAbstractSocket::writeData(), and QUdpSocket::writeDatagram().

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 QProcess::close(), and close().

qint64 QIODevice::readData ( char *  data,
qint64  maxSize 
) [protected, pure virtual]

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

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

See also:
read() readLine() writeData()

Referenced by read().

qint64 QIODevice::readLineData ( char *  data,
qint64  maxSize 
) [protected, virtual]

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 '' byte to data; readLineData() does not need to do this.

Definition at line 1105 of file qiodevice.cpp.

References c, d, getChar(), and printf.

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

01106 {
01107     qint64 readSoFar = 0;
01108     char c;
01109     bool lastGetSucceeded = false;
01110     d_func()->baseReadLineDataCalled = true;
01111 
01112     while (readSoFar < maxSize && (lastGetSucceeded = getChar(&c))) {
01113         *data++ = c;
01114         ++readSoFar;
01115         if (c == '\n')
01116             break;
01117     }
01118 
01119 #if defined QIODEVICE_DEBUG
01120     Q_D(QIODevice);
01121     printf("%p QIODevice::readLineData(%p, %d), d->pos = %d, d->buffer.size() = %d, returns %d\n",
01122            this, data, int(maxSize), int(d->pos), int(d->buffer.size()), int(readSoFar));
01123 #endif
01124     if (!lastGetSucceeded && readSoFar == 0)
01125         return qint64(-1);
01126     return readSoFar;
01127 }

Here is the call graph for this function:

qint64 QIODevice::writeData ( const char *  data,
qint64  maxSize 
) [protected, pure 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.

See also:
read() write()

Referenced by write().

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

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

See also:
openMode() OpenMode

Definition at line 410 of file qiodevice.cpp.

References printf, and QIODevicePrivate::Unset.

Referenced by Q3Socket::close(), QProcess::close(), Q3SocketDevice::close(), PeerWireClient::connectToHostImplementation(), QAbstractSocket::connectToHostImplementation(), Q3Socket::flush(), QTemporaryFile::open(), Q3Socket::open(), QStringBuffer::open(), QFile::open(), Q3SocketDevice::open(), QBuffer::open(), QAbstractSocket::setSocketDescriptor(), and QProcess::start().

00411 {
00412 #if defined QIODEVICE_DEBUG
00413     printf("%p QIODevice::setOpenMode(0x%x)\n", this, int(openMode));
00414 #endif
00415     d_func()->openMode = openMode;
00416     d_func()->accessMode = QIODevicePrivate::Unset;
00417 }

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

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

See also:
errorString()

Definition at line 1422 of file qiodevice.cpp.

Referenced by QUdpSocket::bind(), QAbstractSocket::readData(), QUdpSocket::readDatagram(), QAbstractSocket::setSocketDescriptor(), QAbstractSocket::waitForBytesWritten(), QAbstractSocket::waitForConnected(), QAbstractSocket::waitForDisconnected(), QAbstractSocket::waitForReadyRead(), QAbstractSocket::writeData(), and QUdpSocket::writeDatagram().

01423 {
01424     d_func()->errorString = str;
01425 }


The documentation for this class was generated from the following files:
Generated on Thu Mar 15 18:04:44 2007 for Qt 4.2 User's Guide by  doxygen 1.5.1