1
/****************************************************************************
3
** Copyright (C) 2016 The Qt Company Ltd.
4
** Contact: https://www.qt.io/licensing/
6
** This file is part of the QtCore module of the Qt Toolkit.
8
** $QT_BEGIN_LICENSE:LGPL$
9
** Commercial License Usage
10
** Licensees holding valid commercial Qt licenses may use this file in
11
** accordance with the commercial license agreement provided with the
12
** Software or, alternatively, in accordance with the terms contained in
13
** a written agreement between you and The Qt Company. For licensing terms
14
** and conditions see https://www.qt.io/terms-conditions. For further
15
** information use the contact form at https://www.qt.io/contact-us.
17
** GNU Lesser General Public License Usage
18
** Alternatively, this file may be used under the terms of the GNU Lesser
19
** General Public License version 3 as published by the Free Software
20
** Foundation and appearing in the file LICENSE.LGPL3 included in the
21
** packaging of this file. Please review the following information to
22
** ensure the GNU Lesser General Public License version 3 requirements
23
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25
** GNU General Public License Usage
26
** Alternatively, this file may be used under the terms of the GNU
27
** General Public License version 2.0 or (at your option) the GNU General
28
** Public license version 3 or any later version approved by the KDE Free
29
** Qt Foundation. The licenses are as published by the Free Software
30
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31
** included in the packaging of this file. Please review the following
32
** information to ensure the GNU General Public License requirements will
33
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34
** https://www.gnu.org/licenses/gpl-3.0.html.
38
****************************************************************************/
40
//#define QIODEVICE_DEBUG
42
#include "qbytearray.h"
44
#include "qiodevice_p.h"
46
#include "qstringlist.h"
48
#include "private/qbytearray_p.h"
52
#ifdef QIODEVICE_DEBUG
58
#ifdef QIODEVICE_DEBUG
59
void debugBinaryString(const QByteArray &input)
63
for (int i = 0; i < input.size(); ++i) {
66
if ((i % 16) == 15 || i == (input.size() - 1)) {
67
printf("\n%15d:", startOffset);
68
startOffset += tmp.size();
70
for (int j = 0; j < tmp.size(); ++j)
71
printf(" %02x", int(uchar(tmp[j])));
72
for (int j = tmp.size(); j < 16 + 1; ++j)
74
for (int j = 0; j < tmp.size(); ++j)
75
printf("%c", isprint(int(uchar(tmp[j]))) ? tmp[j] : '.');
82
void debugBinaryString(const char *data, qint64 maxlen)
84
debugBinaryString(QByteArray(data, maxlen));
90
static void checkWarnMessage(const QIODevice *device, const char *function, const char *what)
92
#ifndef QT_NO_WARNING_OUTPUT
93
QDebug d = qWarning();
96
d << "QIODevice::" << function;
98
d << " (" << device->metaObject()->className();
99
if (!device->objectName().isEmpty())
100
d << ", \"" << device->objectName() << '"';
101
if (const QFile *f = qobject_cast<const QFile *>(device))
102
d << ", \"" << QDir::toNativeSeparators(f->fileName()) << '"';
106
#endif // !QT_NO_QOBJECT
112
#endif // QT_NO_WARNING_OUTPUT
115
#define CHECK_MAXLEN(function, returnType) \
118
checkWarnMessage(this, #function, "Called with maxSize < 0"); \
123
#define CHECK_MAXBYTEARRAYSIZE(function) \
125
if (maxSize >= MaxByteArraySize) { \
126
checkWarnMessage(this, #function, "maxSize argument exceeds QByteArray size limit"); \
127
maxSize = MaxByteArraySize - 1; \
131
#define CHECK_WRITABLE(function, returnType) \
133
if ((d->openMode & WriteOnly) == 0) { \
134
if (d->openMode == NotOpen) { \
135
checkWarnMessage(this, #function, "device not open"); \
138
checkWarnMessage(this, #function, "ReadOnly device"); \
143
#define CHECK_READABLE(function, returnType) \
145
if ((d->openMode & ReadOnly) == 0) { \
146
if (d->openMode == NotOpen) { \
147
checkWarnMessage(this, #function, "device not open"); \
150
checkWarnMessage(this, #function, "WriteOnly device"); \
158
QIODevicePrivate::QIODevicePrivate()
159
: openMode(QIODevice::NotOpen),
160
pos(0), devicePos(0),
162
writeChannelCount(0),
163
currentReadChannel(0),
164
currentWriteChannel(0),
165
readBufferChunkSize(QIODEVICE_BUFFERSIZE),
166
writeBufferChunkSize(0),
168
transactionStarted(false)
169
, baseReadLineDataCalled(false)
180
QIODevicePrivate::~QIODevicePrivate()
189
\brief The QIODevice class is the base interface class of all I/O
194
QIODevice provides both a common implementation and an abstract
195
interface for devices that support reading and writing of blocks
196
of data, such as QFile, QBuffer and QTcpSocket. QIODevice is
197
abstract and can not be instantiated, but it is common to use the
198
interface it defines to provide device-independent I/O features.
199
For example, Qt's XML classes operate on a QIODevice pointer,
200
allowing them to be used with various devices (such as files and
203
Before accessing the device, open() must be called to set the
204
correct OpenMode (such as ReadOnly or ReadWrite). You can then
205
write to the device with write() or putChar(), and read by calling
206
either read(), readLine(), or readAll(). Call close() when you are
207
done with the device.
209
QIODevice distinguishes between two types of devices:
210
random-access devices and sequential devices.
213
\li Random-access devices support seeking to arbitrary
214
positions using seek(). The current position in the file is
215
available by calling pos(). QFile and QBuffer are examples of
216
random-access devices.
218
\li Sequential devices don't support seeking to arbitrary
219
positions. The data must be read in one pass. The functions
220
pos() and size() don't work for sequential devices.
221
QTcpSocket and QProcess are examples of sequential devices.
224
You can use isSequential() to determine the type of device.
226
QIODevice emits readyRead() when new data is available for
227
reading; for example, if new data has arrived on the network or if
228
additional data is appended to a file that you are reading
229
from. You can call bytesAvailable() to determine the number of
230
bytes that are currently available for reading. It's common to use
231
bytesAvailable() together with the readyRead() signal when
232
programming with asynchronous devices such as QTcpSocket, where
233
fragments of data can arrive at arbitrary points in
234
time. QIODevice emits the bytesWritten() signal every time a
235
payload of data has been written to the device. Use bytesToWrite()
236
to determine the current amount of data waiting to be written.
238
Certain subclasses of QIODevice, such as QTcpSocket and QProcess,
239
are asynchronous. This means that I/O functions such as write()
240
or read() always return immediately, while communication with the
241
device itself may happen when control goes back to the event loop.
242
QIODevice provides functions that allow you to force these
243
operations to be performed immediately, while blocking the
244
calling thread and without entering the event loop. This allows
245
QIODevice subclasses to be used without an event loop, or in
249
\li waitForReadyRead() - This function suspends operation in the
250
calling thread until new data is available for reading.
252
\li waitForBytesWritten() - This function suspends operation in the
253
calling thread until one payload of data has been written to the
256
\li waitFor....() - Subclasses of QIODevice implement blocking
257
functions for device-specific operations. For example, QProcess
258
has a function called \l {QProcess::}{waitForStarted()} which suspends operation in
259
the calling thread until the process has started.
262
Calling these functions from the main, GUI thread, may cause your
263
user interface to freeze. Example:
265
\snippet code/src_corelib_io_qiodevice.cpp 0
267
By subclassing QIODevice, you can provide the same interface to
268
your own I/O devices. Subclasses of QIODevice are only required to
269
implement the protected readData() and writeData() functions.
270
QIODevice uses these functions to implement all its convenience
271
functions, such as getChar(), readLine() and write(). QIODevice
272
also handles access control for you, so you can safely assume that
273
the device is opened in write mode if writeData() is called.
275
Some subclasses, such as QFile and QTcpSocket, are implemented
276
using a memory buffer for intermediate storing of data. This
277
reduces the number of required device accessing calls, which are
278
often very slow. Buffering makes functions like getChar() and
279
putChar() fast, as they can operate on the memory buffer instead
280
of directly on the device itself. Certain I/O operations, however,
281
don't work well with a buffer. For example, if several users open
282
the same device and read it character by character, they may end
283
up reading the same data when they meant to read a separate chunk
284
each. For this reason, QIODevice allows you to bypass any
285
buffering by passing the Unbuffered flag to open(). When
286
subclassing QIODevice, remember to bypass any buffer you may use
287
when the device is open in Unbuffered mode.
289
Usually, the incoming data stream from an asynchronous device is
290
fragmented, and chunks of data can arrive at arbitrary points in time.
291
To handle incomplete reads of data structures, use the transaction
292
mechanism implemented by QIODevice. See startTransaction() and related
293
functions for more details.
295
Some sequential devices support communicating via multiple channels. These
296
channels represent separate streams of data that have the property of
297
independently sequenced delivery. Once the device is opened, you can
298
determine the number of channels by calling the readChannelCount() and
299
writeChannelCount() functions. To switch between channels, call
300
setCurrentReadChannel() and setCurrentWriteChannel(), respectively.
301
QIODevice also provides additional signals to handle asynchronous
302
communication on a per-channel basis.
304
\sa QBuffer, QFile, QTcpSocket
308
\enum QIODevice::OpenModeFlag
310
This enum is used with open() to describe the mode in which a device
311
is opened. It is also returned by openMode().
313
\value NotOpen The device is not open.
314
\value ReadOnly The device is open for reading.
315
\value WriteOnly The device is open for writing. Note that this mode implies
317
\value ReadWrite The device is open for reading and writing.
318
\value Append The device is opened in append mode so that all data is
319
written to the end of the file.
320
\value Truncate If possible, the device is truncated before it is opened.
321
All earlier contents of the device are lost.
322
\value Text When reading, the end-of-line terminators are
323
translated to '\\n'. When writing, the end-of-line
324
terminators are translated to the local encoding, for
325
example '\\r\\n' for Win32.
326
\value Unbuffered Any buffer in the device is bypassed.
328
Certain flags, such as \c Unbuffered and \c Truncate, are
329
meaningless when used with some subclasses. Some of these
330
restrictions are implied by the type of device that is represented
331
by a subclass. In other cases, the restriction may be due to the
332
implementation, or may be imposed by the underlying platform; for
333
example, QTcpSocket does not support \c Unbuffered mode, and
334
limitations in the native API prevent QFile from supporting \c
335
Unbuffered on Windows.
338
/*! \fn QIODevice::bytesWritten(qint64 bytes)
340
This signal is emitted every time a payload of data has been
341
written to the device's current write channel. The \a bytes argument is
342
set to the number of bytes that were written in this payload.
344
bytesWritten() is not emitted recursively; if you reenter the event loop
345
or call waitForBytesWritten() inside a slot connected to the
346
bytesWritten() signal, the signal will not be reemitted (although
347
waitForBytesWritten() may still return true).
353
\fn QIODevice::channelBytesWritten(int channel, qint64 bytes)
356
This signal is emitted every time a payload of data has been written to
357
the device. The \a bytes argument is set to the number of bytes that were
358
written in this payload, while \a channel is the channel they were written
359
to. Unlike bytesWritten(), it is emitted regardless of the
360
\l{currentWriteChannel()}{current write channel}.
362
channelBytesWritten() can be emitted recursively - even for the same
365
\sa bytesWritten(), channelReadyRead()
369
\fn QIODevice::readyRead()
371
This signal is emitted once every time new data is available for
372
reading from the device's current read channel. It will only be emitted
373
again once new data is available, such as when a new payload of network
374
data has arrived on your network socket, or when a new block of data has
375
been appended to your device.
377
readyRead() is not emitted recursively; if you reenter the event loop or
378
call waitForReadyRead() inside a slot connected to the readyRead() signal,
379
the signal will not be reemitted (although waitForReadyRead() may still
382
Note for developers implementing classes derived from QIODevice:
383
you should always emit readyRead() when new data has arrived (do not
384
emit it only because there's data still to be read in your
385
buffers). Do not emit readyRead() in other conditions.
391
\fn QIODevice::channelReadyRead(int channel)
394
This signal is emitted when new data is available for reading from the
395
device. The \a channel argument is set to the index of the read channel on
396
which the data has arrived. Unlike readyRead(), it is emitted regardless of
397
the \l{currentReadChannel()}{current read channel}.
399
channelReadyRead() can be emitted recursively - even for the same channel.
401
\sa readyRead(), channelBytesWritten()
404
/*! \fn QIODevice::aboutToClose()
406
This signal is emitted when the device is about to close. Connect
407
this signal if you have operations that need to be performed
408
before the device closes (e.g., if you have data in a separate
409
buffer that needs to be written to the device).
413
\fn QIODevice::readChannelFinished()
416
This signal is emitted when the input (reading) stream is closed
417
in this device. It is emitted as soon as the closing is detected,
418
which means that there might still be data available for reading
425
QIODevice::QIODevice()
426
: d_ptr(new QIODevicePrivate)
434
QIODevice::QIODevice(QIODevicePrivate &dd)
442
Constructs a QIODevice object.
445
QIODevice::QIODevice()
446
: QObject(*new QIODevicePrivate, 0)
448
#if defined QIODEVICE_DEBUG
449
QFile *file = qobject_cast<QFile *>(this);
450
printf("%p QIODevice::QIODevice(\"%s\") %s\n", this, metaObject()->className(),
451
qPrintable(file ? file->fileName() : QString()));
456
Constructs a QIODevice object with the given \a parent.
459
QIODevice::QIODevice(QObject *parent)
460
: QObject(*new QIODevicePrivate, parent)
462
#if defined QIODEVICE_DEBUG
463
printf("%p QIODevice::QIODevice(%p \"%s\")\n", this, parent, metaObject()->className());
470
QIODevice::QIODevice(QIODevicePrivate &dd, QObject *parent)
471
: QObject(dd, parent)
478
The destructor is virtual, and QIODevice is an abstract base
479
class. This destructor does not call close(), but the subclass
480
destructor might. If you are in doubt, call close() before
481
destroying the QIODevice.
483
QIODevice::~QIODevice()
485
#if defined QIODEVICE_DEBUG
486
printf("%p QIODevice::~QIODevice()\n", this);
491
Returns \c true if this device is sequential; otherwise returns
494
Sequential devices, as opposed to a random-access devices, have no
495
concept of a start, an end, a size, or a current position, and they
496
do not support seeking. You can only read from the device when it
497
reports that data is available. The most common example of a
498
sequential device is a network socket. On Unix, special files such
499
as /dev/zero and fifo pipes are sequential.
501
Regular files, on the other hand, do support random access. They
502
have both a size and a current position, and they also support
503
seeking backwards and forwards in the data stream. Regular files
508
bool QIODevice::isSequential() const
514
Returns the mode in which the device has been opened;
515
i.e. ReadOnly or WriteOnly.
519
QIODevice::OpenMode QIODevice::openMode() const
521
return d_func()->openMode;
525
Sets the OpenMode of the device to \a openMode. Call this
526
function to set the open mode if the flags change after the device
529
\sa openMode(), OpenMode
531
void QIODevice::setOpenMode(OpenMode openMode)
534
#if defined QIODEVICE_DEBUG
535
printf("%p QIODevice::setOpenMode(0x%x)\n", this, int(openMode));
537
d->openMode = openMode;
538
d->accessMode = QIODevicePrivate::Unset;
539
d->setReadChannelCount(isReadable() ? qMax(d->readChannelCount, 1) : 0);
540
d->setWriteChannelCount(isWritable() ? qMax(d->writeChannelCount, 1) : 0);
544
If \a enabled is true, this function sets the \l Text flag on the device;
545
otherwise the \l Text flag is removed. This feature is useful for classes
546
that provide custom end-of-line handling on a QIODevice.
548
The IO device should be opened before calling this function.
550
\sa open(), setOpenMode()
552
void QIODevice::setTextModeEnabled(bool enabled)
556
checkWarnMessage(this, "setTextModeEnabled", "The device is not open");
562
d->openMode &= ~Text;
566
Returns \c true if the \l Text flag is enabled; otherwise returns \c false.
568
\sa setTextModeEnabled()
570
bool QIODevice::isTextModeEnabled() const
572
return d_func()->openMode & Text;
576
Returns \c true if the device is open; otherwise returns \c false. A
577
device is open if it can be read from and/or written to. By
578
default, this function returns \c false if openMode() returns
581
\sa openMode(), OpenMode
583
bool QIODevice::isOpen() const
585
return d_func()->openMode != NotOpen;
589
Returns \c true if data can be read from the device; otherwise returns
590
false. Use bytesAvailable() to determine how many bytes can be read.
592
This is a convenience function which checks if the OpenMode of the
593
device contains the ReadOnly flag.
595
\sa openMode(), OpenMode
597
bool QIODevice::isReadable() const
599
return (openMode() & ReadOnly) != 0;
603
Returns \c true if data can be written to the device; otherwise returns
606
This is a convenience function which checks if the OpenMode of the
607
device contains the WriteOnly flag.
609
\sa openMode(), OpenMode
611
bool QIODevice::isWritable() const
613
return (openMode() & WriteOnly) != 0;
619
Returns the number of available read channels if the device is open;
622
\sa writeChannelCount(), QProcess
624
int QIODevice::readChannelCount() const
626
return d_func()->readChannelCount;
632
Returns the number of available write channels if the device is open;
635
\sa readChannelCount()
637
int QIODevice::writeChannelCount() const
639
return d_func()->writeChannelCount;
645
Returns the index of the current read channel.
647
\sa setCurrentReadChannel(), readChannelCount(), QProcess
649
int QIODevice::currentReadChannel() const
651
return d_func()->currentReadChannel;
657
Sets the current read channel of the QIODevice to the given \a
658
channel. The current input channel is used by the functions
659
read(), readAll(), readLine(), and getChar(). It also determines
660
which channel triggers QIODevice to emit readyRead().
662
\sa currentReadChannel(), readChannelCount(), QProcess
664
void QIODevice::setCurrentReadChannel(int channel)
668
if (d->transactionStarted) {
669
checkWarnMessage(this, "setReadChannel", "Failed due to read transaction being in progress");
673
#if defined QIODEVICE_DEBUG
674
qDebug("%p QIODevice::setCurrentReadChannel(%d), d->currentReadChannel = %d, d->readChannelCount = %d\n",
675
this, channel, d->currentReadChannel, d->readChannelCount);
678
d->setCurrentReadChannel(channel);
684
void QIODevicePrivate::setReadChannelCount(int count)
686
if (count > readBuffers.size()) {
687
readBuffers.insert(readBuffers.end(), count - readBuffers.size(),
688
QRingBuffer(readBufferChunkSize));
690
readBuffers.resize(count);
692
readChannelCount = count;
693
setCurrentReadChannel(currentReadChannel);
699
Returns the the index of the current write channel.
701
\sa setCurrentWriteChannel(), writeChannelCount()
703
int QIODevice::currentWriteChannel() const
705
return d_func()->currentWriteChannel;
711
Sets the current write channel of the QIODevice to the given \a
712
channel. The current output channel is used by the functions
713
write(), putChar(). It also determines which channel triggers
714
QIODevice to emit bytesWritten().
716
\sa currentWriteChannel(), writeChannelCount()
718
void QIODevice::setCurrentWriteChannel(int channel)
722
#if defined QIODEVICE_DEBUG
723
qDebug("%p QIODevice::setCurrentWriteChannel(%d), d->currentWriteChannel = %d, d->writeChannelCount = %d\n",
724
this, channel, d->currentWriteChannel, d->writeChannelCount);
727
d->setCurrentWriteChannel(channel);
733
void QIODevicePrivate::setWriteChannelCount(int count)
735
if (count > writeBuffers.size()) {
736
// If writeBufferChunkSize is zero (default value), we don't use
737
// QIODevice's write buffers.
738
if (writeBufferChunkSize != 0) {
739
writeBuffers.insert(writeBuffers.end(), count - writeBuffers.size(),
740
QRingBuffer(writeBufferChunkSize));
743
writeBuffers.resize(count);
745
writeChannelCount = count;
746
setCurrentWriteChannel(currentWriteChannel);
750
Opens the device and sets its OpenMode to \a mode. Returns \c true if successful;
751
otherwise returns \c false. This function should be called from any
752
reimplementations of open() or other functions that open the device.
754
\sa openMode(), OpenMode
756
bool QIODevice::open(OpenMode mode)
760
d->pos = (mode & Append) ? size() : qint64(0);
761
d->accessMode = QIODevicePrivate::Unset;
762
d->readBuffers.clear();
763
d->writeBuffers.clear();
764
d->setReadChannelCount(isReadable() ? 1 : 0);
765
d->setWriteChannelCount(isWritable() ? 1 : 0);
766
#if defined QIODEVICE_DEBUG
767
printf("%p QIODevice::open(0x%x)\n", this, quint32(mode));
773
First emits aboutToClose(), then closes the device and sets its
774
OpenMode to NotOpen. The error string is also reset.
776
\sa setOpenMode(), OpenMode
778
void QIODevice::close()
781
if (d->openMode == NotOpen)
784
#if defined QIODEVICE_DEBUG
785
printf("%p QIODevice::close()\n", this);
788
#ifndef QT_NO_QOBJECT
791
d->openMode = NotOpen;
792
d->errorString.clear();
794
d->transactionStarted = false;
795
d->transactionPos = 0;
796
d->setReadChannelCount(0);
797
// Do not clear write buffers to allow delayed close in sockets
798
d->writeChannelCount = 0;
802
For random-access devices, this function returns the position that
803
data is written to or read from. For sequential devices or closed
804
devices, where there is no concept of a "current position", 0 is
807
The current read/write position of the device is maintained internally by
808
QIODevice, so reimplementing this function is not necessary. When
809
subclassing QIODevice, use QIODevice::seek() to notify QIODevice about
810
changes in the device position.
812
\sa isSequential(), seek()
814
qint64 QIODevice::pos() const
816
Q_D(const QIODevice);
817
#if defined QIODEVICE_DEBUG
818
printf("%p QIODevice::pos() == %lld\n", this, d->pos);
824
For open random-access devices, this function returns the size of the
825
device. For open sequential devices, bytesAvailable() is returned.
827
If the device is closed, the size returned will not reflect the actual
830
\sa isSequential(), pos()
832
qint64 QIODevice::size() const
834
return d_func()->isSequential() ? bytesAvailable() : qint64(0);
838
For random-access devices, this function sets the current position
839
to \a pos, returning true on success, or false if an error occurred.
840
For sequential devices, the default behavior is to produce a warning
843
When subclassing QIODevice, you must call QIODevice::seek() at the
844
start of your function to ensure integrity with QIODevice's
847
\sa pos(), isSequential()
849
bool QIODevice::seek(qint64 pos)
852
if (d->isSequential()) {
853
checkWarnMessage(this, "seek", "Cannot call seek on a sequential device");
856
if (d->openMode == NotOpen) {
857
checkWarnMessage(this, "seek", "The device is not open");
861
qWarning("QIODevice::seek: Invalid pos: %lld", pos);
865
#if defined QIODEVICE_DEBUG
866
printf("%p QIODevice::seek(%lld), before: d->pos = %lld, d->buffer.size() = %lld\n",
867
this, pos, d->pos, d->buffer.size());
873
#if defined QIODEVICE_DEBUG
874
printf("%p \tafter: d->pos == %lld, d->buffer.size() == %lld\n", this, d->pos,
883
void QIODevicePrivate::seekBuffer(qint64 newPos)
885
const qint64 offset = newPos - pos;
888
if (offset < 0 || offset >= buffer.size()) {
889
// When seeking backwards, an operation that is only allowed for
890
// random-access devices, the buffer is cleared. The next read
891
// operation will then refill the buffer.
899
Returns \c true if the current read and write position is at the end
900
of the device (i.e. there is no more data available for reading on
901
the device); otherwise returns \c false.
903
For some devices, atEnd() can return true even though there is more data
904
to read. This special case only applies to devices that generate data in
905
direct response to you calling read() (e.g., \c /dev or \c /proc files on
906
Unix and \macos, or console input / \c stdin on all platforms).
908
\sa bytesAvailable(), read(), isSequential()
910
bool QIODevice::atEnd() const
912
Q_D(const QIODevice);
913
const bool result = (d->openMode == NotOpen || (d->isBufferEmpty()
914
&& bytesAvailable() == 0));
915
#if defined QIODEVICE_DEBUG
916
printf("%p QIODevice::atEnd() returns %s, d->openMode == %d, d->pos == %lld\n", this,
917
result ? "true" : "false", int(d->openMode), d->pos);
923
Seeks to the start of input for random-access devices. Returns
924
true on success; otherwise returns \c false (for example, if the
927
Note that when using a QTextStream on a QFile, calling reset() on
928
the QFile will not have the expected result because QTextStream
929
buffers the file. Use the QTextStream::seek() function instead.
933
bool QIODevice::reset()
935
#if defined QIODEVICE_DEBUG
936
printf("%p QIODevice::reset()\n", this);
942
Returns the number of bytes that are available for reading. This
943
function is commonly used with sequential devices to determine the
944
number of bytes to allocate in a buffer before reading.
946
Subclasses that reimplement this function must call the base
947
implementation in order to include the size of the buffer of QIODevice. Example:
949
\snippet code/src_corelib_io_qiodevice.cpp 1
951
\sa bytesToWrite(), readyRead(), isSequential()
953
qint64 QIODevice::bytesAvailable() const
955
Q_D(const QIODevice);
956
if (!d->isSequential())
957
return qMax(size() - d->pos, qint64(0));
958
return d->buffer.size() - d->transactionPos;
961
/*! For buffered devices, this function returns the number of bytes
962
waiting to be written. For devices with no buffer, this function
965
Subclasses that reimplement this function must call the base
966
implementation in order to include the size of the buffer of QIODevice.
968
\sa bytesAvailable(), bytesWritten(), isSequential()
970
qint64 QIODevice::bytesToWrite() const
972
return d_func()->writeBuffer.size();
976
Reads at most \a maxSize bytes from the device into \a data, and
977
returns the number of bytes read. If an error occurs, such as when
978
attempting to read from a device opened in WriteOnly mode, this
981
0 is returned when no more data is available for reading. However,
982
reading past the end of the stream is considered an error, so this
983
function returns -1 in those cases (that is, reading on a closed
984
socket or after a process has died).
986
\sa readData(), readLine(), write()
988
qint64 QIODevice::read(char *data, qint64 maxSize)
992
#if defined QIODEVICE_DEBUG
993
printf("%p QIODevice::read(%p, %lld), d->pos = %lld, d->buffer.size() = %lld\n",
994
this, data, maxSize, d->pos, d->buffer.size());
997
const bool sequential = d->isSequential();
998
const bool keepDataInBuffer = sequential && d->transactionStarted;
1000
// Short circuit for getChar()
1001
if (maxSize == 1 && !keepDataInBuffer) {
1003
while ((chint = d->buffer.getChar()) != -1) {
1007
char c = char(uchar(chint));
1008
if (c == '\r' && (d->openMode & Text))
1011
#if defined QIODEVICE_DEBUG
1012
printf("%p \tread 0x%hhx (%c) returning 1 (shortcut)\n", this,
1013
int(c), isprint(c) ? c : '?');
1015
if (d->buffer.isEmpty())
1021
CHECK_MAXLEN(read, qint64(-1));
1022
qint64 readSoFar = 0;
1023
bool madeBufferReadsOnly = true;
1024
bool deviceAtEof = false;
1025
char *readPtr = data;
1027
// Try reading from the buffer.
1028
qint64 bufferReadChunkSize = keepDataInBuffer
1029
? d->buffer.peek(data, maxSize, d->transactionPos)
1030
: d->buffer.read(data, maxSize);
1031
if (bufferReadChunkSize > 0) {
1032
if (keepDataInBuffer)
1033
d->transactionPos += bufferReadChunkSize;
1034
else if (!sequential)
1035
d->pos += bufferReadChunkSize;
1036
readSoFar += bufferReadChunkSize;
1037
data += bufferReadChunkSize;
1038
maxSize -= bufferReadChunkSize;
1039
#if defined QIODEVICE_DEBUG
1040
printf("%p \treading %lld bytes from buffer into position %lld\n", this,
1041
bufferReadChunkSize, readSoFar - bufferReadChunkSize);
1044
CHECK_READABLE(read, qint64(-1));
1047
if (maxSize > 0 && !deviceAtEof) {
1048
qint64 readFromDevice = 0;
1049
// Make sure the device is positioned correctly.
1050
if (sequential || d->pos == d->devicePos || seek(d->pos)) {
1051
madeBufferReadsOnly = false; // fix readData attempt
1052
if ((maxSize >= d->readBufferChunkSize || (d->openMode & Unbuffered))
1053
&& !keepDataInBuffer) {
1054
// Read big chunk directly to output buffer
1055
readFromDevice = readData(data, maxSize);
1056
deviceAtEof = (readFromDevice != maxSize);
1057
#if defined QIODEVICE_DEBUG
1058
printf("%p \treading %lld bytes from device (total %lld)\n", this,
1059
readFromDevice, readSoFar);
1061
if (readFromDevice > 0) {
1062
readSoFar += readFromDevice;
1063
data += readFromDevice;
1064
maxSize -= readFromDevice;
1066
d->pos += readFromDevice;
1067
d->devicePos += readFromDevice;
1071
// Do not read more than maxSize on unbuffered devices
1072
const qint64 bytesToBuffer = (d->openMode & Unbuffered)
1073
? qMin(maxSize, qint64(d->readBufferChunkSize))
1074
: qint64(d->readBufferChunkSize);
1075
// Try to fill QIODevice buffer by single read
1076
readFromDevice = readData(d->buffer.reserve(bytesToBuffer), bytesToBuffer);
1077
deviceAtEof = (readFromDevice != bytesToBuffer);
1078
d->buffer.chop(bytesToBuffer - qMax(Q_INT64_C(0), readFromDevice));
1079
if (readFromDevice > 0) {
1081
d->devicePos += readFromDevice;
1082
#if defined QIODEVICE_DEBUG
1083
printf("%p \treading %lld from device into buffer\n", this,
1090
readFromDevice = -1;
1093
if (readFromDevice < 0 && readSoFar == 0) {
1094
// error and we haven't read anything: return immediately
1099
if ((d->openMode & Text) && readPtr < data) {
1100
const char *endPtr = data;
1102
// optimization to avoid initial self-assignment
1103
while (*readPtr != '\r') {
1104
if (++readPtr == endPtr)
1108
char *writePtr = readPtr;
1110
while (readPtr < endPtr) {
1111
char ch = *readPtr++;
1121
// Make sure we get more data if there is room for more. This
1122
// is very important for when someone seeks to the start of a
1123
// '\r\n' and reads one character - they should get the '\n'.
1131
#if defined QIODEVICE_DEBUG
1132
printf("%p \treturning %lld, d->pos == %lld, d->buffer.size() == %lld\n", this,
1133
readSoFar, d->pos, d->buffer.size());
1134
debugBinaryString(data - readSoFar, readSoFar);
1137
if (madeBufferReadsOnly && d->isBufferEmpty())
1146
Reads at most \a maxSize bytes from the device, and returns the
1147
data read as a QByteArray.
1149
This function has no way of reporting errors; returning an empty
1150
QByteArray can mean either that no data was currently available
1151
for reading, or that an error occurred.
1154
QByteArray QIODevice::read(qint64 maxSize)
1159
CHECK_MAXLEN(read, result);
1160
CHECK_MAXBYTEARRAYSIZE(read);
1162
#if defined QIODEVICE_DEBUG
1163
printf("%p QIODevice::read(%lld), d->pos = %lld, d->buffer.size() = %lld\n",
1164
this, maxSize, d->pos, d->buffer.size());
1167
qint64 readBytes = 0;
1169
result.resize(int(maxSize));
1170
if (!result.size()) {
1171
// If resize fails, read incrementally.
1174
result.resize(int(qMin(maxSize, qint64(result.size() + d->readBufferChunkSize))));
1175
readResult = read(result.data() + readBytes, result.size() - readBytes);
1176
if (readResult > 0 || readBytes == 0)
1177
readBytes += readResult;
1178
} while (readResult == d->readBufferChunkSize);
1180
readBytes = read(result.data(), result.size());
1187
result.resize(int(readBytes));
1193
Reads all remaining data from the device, and returns it as a
1196
This function has no way of reporting errors; returning an empty
1197
QByteArray can mean either that no data was currently available
1198
for reading, or that an error occurred.
1200
QByteArray QIODevice::readAll()
1203
#if defined QIODEVICE_DEBUG
1204
printf("%p QIODevice::readAll(), d->pos = %lld, d->buffer.size() = %lld\n",
1205
this, d->pos, d->buffer.size());
1209
qint64 readBytes = (d->isSequential() ? Q_INT64_C(0) : size());
1210
if (readBytes == 0) {
1211
// Size is unknown, read incrementally.
1212
qint64 readChunkSize = qMax(qint64(d->readBufferChunkSize),
1213
d->isSequential() ? (d->buffer.size() - d->transactionPos)
1214
: d->buffer.size());
1217
if (readBytes + readChunkSize >= MaxByteArraySize) {
1218
// If resize would fail, don't read more, return what we have.
1221
result.resize(readBytes + readChunkSize);
1222
readResult = read(result.data() + readBytes, readChunkSize);
1223
if (readResult > 0 || readBytes == 0) {
1224
readBytes += readResult;
1225
readChunkSize = d->readBufferChunkSize;
1227
} while (readResult > 0);
1229
// Read it all in one go.
1230
// If resize fails, don't read anything.
1231
readBytes -= d->pos;
1232
if (readBytes >= MaxByteArraySize)
1233
return QByteArray();
1234
result.resize(readBytes);
1235
readBytes = read(result.data(), readBytes);
1241
result.resize(int(readBytes));
1247
This function reads a line of ASCII characters from the device, up
1248
to a maximum of \a maxSize - 1 bytes, stores the characters in \a
1249
data, and returns the number of bytes read. If a line could not be
1250
read but no error ocurred, this function returns 0. If an error
1251
occurs, this function returns the length of what could be read, or
1252
-1 if nothing was read.
1254
A terminating '\\0' byte is always appended to \a data, so \a
1255
maxSize must be larger than 1.
1257
Data is read until either of the following conditions are met:
1260
\li The first '\\n' character is read.
1261
\li \a maxSize - 1 bytes are read.
1262
\li The end of the device data is detected.
1265
For example, the following code reads a line of characters from a
1268
\snippet code/src_corelib_io_qiodevice.cpp 2
1270
The newline character ('\\n') is included in the buffer. If a
1271
newline is not encountered before maxSize - 1 bytes are read, a
1272
newline will not be inserted into the buffer. On windows newline
1273
characters are replaced with '\\n'.
1275
This function calls readLineData(), which is implemented using
1276
repeated calls to getChar(). You can provide a more efficient
1277
implementation by reimplementing readLineData() in your own
1280
\sa getChar(), read(), write()
1282
qint64 QIODevice::readLine(char *data, qint64 maxSize)
1286
checkWarnMessage(this, "readLine", "Called with maxSize < 2");
1290
#if defined QIODEVICE_DEBUG
1291
printf("%p QIODevice::readLine(%p, %lld), d->pos = %lld, d->buffer.size() = %lld\n",
1292
this, data, maxSize, d->pos, d->buffer.size());
1295
// Leave room for a '\0'
1298
const bool sequential = d->isSequential();
1299
const bool keepDataInBuffer = sequential && d->transactionStarted;
1301
qint64 readSoFar = 0;
1302
if (keepDataInBuffer) {
1303
if (d->transactionPos < d->buffer.size()) {
1304
// Peek line from the specified position
1305
const qint64 i = d->buffer.indexOf('\n', maxSize, d->transactionPos);
1306
readSoFar = d->buffer.peek(data, i >= 0 ? (i - d->transactionPos + 1) : maxSize,
1308
d->transactionPos += readSoFar;
1309
if (d->transactionPos == d->buffer.size())
1312
} else if (!d->buffer.isEmpty()) {
1313
// QRingBuffer::readLine() terminates the line with '\0'
1314
readSoFar = d->buffer.readLine(data, maxSize + 1);
1315
if (d->buffer.isEmpty())
1318
d->pos += readSoFar;
1322
#if defined QIODEVICE_DEBUG
1323
printf("%p \tread from buffer: %lld bytes, last character read: %hhx\n", this,
1324
readSoFar, data[readSoFar - 1]);
1325
debugBinaryString(data, int(readSoFar));
1327
if (data[readSoFar - 1] == '\n') {
1328
if (d->openMode & Text) {
1329
// QRingBuffer::readLine() isn't Text aware.
1330
if (readSoFar > 1 && data[readSoFar - 2] == '\r') {
1332
data[readSoFar - 1] = '\n';
1335
data[readSoFar] = '\0';
1340
if (d->pos != d->devicePos && !sequential && !seek(d->pos))
1342
d->baseReadLineDataCalled = false;
1343
// Force base implementation for transaction on sequential device
1344
// as it stores the data in internal buffer automatically.
1345
qint64 readBytes = keepDataInBuffer
1346
? QIODevice::readLineData(data + readSoFar, maxSize - readSoFar)
1347
: readLineData(data + readSoFar, maxSize - readSoFar);
1348
#if defined QIODEVICE_DEBUG
1349
printf("%p \tread from readLineData: %lld bytes, readSoFar = %lld bytes\n", this,
1350
readBytes, readSoFar);
1351
if (readBytes > 0) {
1352
debugBinaryString(data, int(readSoFar + readBytes));
1355
if (readBytes < 0) {
1356
data[readSoFar] = '\0';
1357
return readSoFar ? readSoFar : -1;
1359
readSoFar += readBytes;
1360
if (!d->baseReadLineDataCalled && !sequential) {
1361
d->pos += readBytes;
1362
// If the base implementation was not called, then we must
1363
// assume the device position is invalid and force a seek.
1364
d->devicePos = qint64(-1);
1366
data[readSoFar] = '\0';
1368
if (d->openMode & Text) {
1369
if (readSoFar > 1 && data[readSoFar - 1] == '\n' && data[readSoFar - 2] == '\r') {
1370
data[readSoFar - 2] = '\n';
1371
data[readSoFar - 1] = '\0';
1376
#if defined QIODEVICE_DEBUG
1377
printf("%p \treturning %lld, d->pos = %lld, d->buffer.size() = %lld, size() = %lld\n",
1378
this, readSoFar, d->pos, d->buffer.size(), size());
1379
debugBinaryString(data, int(readSoFar));
1387
Reads a line from the device, but no more than \a maxSize characters,
1388
and returns the result as a byte array.
1390
This function has no way of reporting errors; returning an empty
1391
QByteArray can mean either that no data was currently available
1392
for reading, or that an error occurred.
1394
QByteArray QIODevice::readLine(qint64 maxSize)
1399
CHECK_MAXLEN(readLine, result);
1400
CHECK_MAXBYTEARRAYSIZE(readLine);
1402
#if defined QIODEVICE_DEBUG
1403
printf("%p QIODevice::readLine(%lld), d->pos = %lld, d->buffer.size() = %lld\n",
1404
this, maxSize, d->pos, d->buffer.size());
1407
result.resize(int(maxSize));
1408
qint64 readBytes = 0;
1409
if (!result.size()) {
1410
// If resize fails or maxSize == 0, read incrementally
1412
maxSize = MaxByteArraySize - 1;
1414
// The first iteration needs to leave an extra byte for the terminating null
1419
result.resize(int(qMin(maxSize, qint64(result.size() + d->readBufferChunkSize))));
1420
readResult = readLine(result.data() + readBytes, result.size() - readBytes);
1421
if (readResult > 0 || readBytes == 0)
1422
readBytes += readResult;
1423
} while (readResult == d->readBufferChunkSize
1424
&& result[int(readBytes - 1)] != '\n');
1426
readBytes = readLine(result.data(), result.size());
1431
result.resize(readBytes);
1437
Reads up to \a maxSize characters into \a data and returns the
1438
number of characters read.
1440
This function is called by readLine(), and provides its base
1441
implementation, using getChar(). Buffered devices can improve the
1442
performance of readLine() by reimplementing this function.
1444
readLine() appends a '\\0' byte to \a data; readLineData() does not
1447
If you reimplement this function, be careful to return the correct
1448
value: it should return the number of bytes read in this line,
1449
including the terminating newline, or 0 if there is no line to be
1450
read at this point. If an error occurs, it should return -1 if and
1451
only if no bytes were read. Reading past EOF is considered an error.
1453
qint64 QIODevice::readLineData(char *data, qint64 maxSize)
1456
qint64 readSoFar = 0;
1458
int lastReadReturn = 0;
1459
d->baseReadLineDataCalled = true;
1461
while (readSoFar < maxSize && (lastReadReturn = read(&c, 1)) == 1) {
1468
#if defined QIODEVICE_DEBUG
1469
printf("%p QIODevice::readLineData(%p, %lld), d->pos = %lld, d->buffer.size() = %lld, "
1470
"returns %lld\n", this, data, maxSize, d->pos, d->buffer.size(), readSoFar);
1472
if (lastReadReturn != 1 && readSoFar == 0)
1473
return isSequential() ? lastReadReturn : -1;
1478
Returns \c true if a complete line of data can be read from the device;
1479
otherwise returns \c false.
1481
Note that unbuffered devices, which have no way of determining what
1482
can be read, always return false.
1484
This function is often called in conjunction with the readyRead()
1487
Subclasses that reimplement this function must call the base
1488
implementation in order to include the contents of the QIODevice's buffer. Example:
1490
\snippet code/src_corelib_io_qiodevice.cpp 3
1492
\sa readyRead(), readLine()
1494
bool QIODevice::canReadLine() const
1496
Q_D(const QIODevice);
1497
return d->buffer.indexOf('\n', d->buffer.size(),
1498
d->isSequential() ? d->transactionPos : Q_INT64_C(0)) >= 0;
1504
Starts a new read transaction on the device.
1506
Defines a restorable point within the sequence of read operations. For
1507
sequential devices, read data will be duplicated internally to allow
1508
recovery in case of incomplete reads. For random-access devices,
1509
this function saves the current position. Call commitTransaction() or
1510
rollbackTransaction() to finish the transaction.
1512
\note Nesting transactions is not supported.
1514
\sa commitTransaction(), rollbackTransaction()
1516
void QIODevice::startTransaction()
1519
if (d->transactionStarted) {
1520
checkWarnMessage(this, "startTransaction", "Called while transaction already in progress");
1523
d->transactionPos = d->pos;
1524
d->transactionStarted = true;
1530
Completes a read transaction.
1532
For sequential devices, all data recorded in the internal buffer during
1533
the transaction will be discarded.
1535
\sa startTransaction(), rollbackTransaction()
1537
void QIODevice::commitTransaction()
1540
if (!d->transactionStarted) {
1541
checkWarnMessage(this, "commitTransaction", "Called while no transaction in progress");
1544
if (d->isSequential())
1545
d->buffer.free(d->transactionPos);
1546
d->transactionStarted = false;
1547
d->transactionPos = 0;
1553
Rolls back a read transaction.
1555
Restores the input stream to the point of the startTransaction() call.
1556
This function is commonly used to rollback the transaction when an
1557
incomplete read was detected prior to committing the transaction.
1559
\sa startTransaction(), commitTransaction()
1561
void QIODevice::rollbackTransaction()
1564
if (!d->transactionStarted) {
1565
checkWarnMessage(this, "rollbackTransaction", "Called while no transaction in progress");
1568
if (!d->isSequential())
1569
d->seekBuffer(d->transactionPos);
1570
d->transactionStarted = false;
1571
d->transactionPos = 0;
1577
Returns \c true if a transaction is in progress on the device, otherwise
1580
\sa startTransaction()
1582
bool QIODevice::isTransactionStarted() const
1584
return d_func()->transactionStarted;
1588
Writes at most \a maxSize bytes of data from \a data to the
1589
device. Returns the number of bytes that were actually written, or
1590
-1 if an error occurred.
1592
\sa read(), writeData()
1594
qint64 QIODevice::write(const char *data, qint64 maxSize)
1597
CHECK_WRITABLE(write, qint64(-1));
1598
CHECK_MAXLEN(write, qint64(-1));
1600
const bool sequential = d->isSequential();
1601
// Make sure the device is positioned correctly.
1602
if (d->pos != d->devicePos && !sequential && !seek(d->pos))
1606
if (d->openMode & Text) {
1607
const char *endOfData = data + maxSize;
1608
const char *startOfBlock = data;
1610
qint64 writtenSoFar = 0;
1611
const qint64 savedPos = d->pos;
1614
const char *endOfBlock = startOfBlock;
1615
while (endOfBlock < endOfData && *endOfBlock != '\n')
1618
qint64 blockSize = endOfBlock - startOfBlock;
1619
if (blockSize > 0) {
1620
qint64 ret = writeData(startOfBlock, blockSize);
1622
if (writtenSoFar && !sequential)
1623
d->buffer.skip(d->pos - savedPos);
1624
return writtenSoFar ? writtenSoFar : ret;
1628
d->devicePos += ret;
1630
writtenSoFar += ret;
1633
if (endOfBlock == endOfData)
1636
qint64 ret = writeData("\r\n", 2);
1638
if (writtenSoFar && !sequential)
1639
d->buffer.skip(d->pos - savedPos);
1640
return writtenSoFar ? writtenSoFar : ret;
1644
d->devicePos += ret;
1648
startOfBlock = endOfBlock + 1;
1651
if (writtenSoFar && !sequential)
1652
d->buffer.skip(d->pos - savedPos);
1653
return writtenSoFar;
1657
qint64 written = writeData(data, maxSize);
1658
if (!sequential && written > 0) {
1660
d->devicePos += written;
1661
d->buffer.skip(written);
1671
Writes data from a zero-terminated string of 8-bit characters to the
1672
device. Returns the number of bytes that were actually written, or
1673
-1 if an error occurred. This is equivalent to
1676
QIODevice::write(data, qstrlen(data));
1680
\sa read(), writeData()
1682
qint64 QIODevice::write(const char *data)
1684
return write(data, qstrlen(data));
1687
/*! \fn qint64 QIODevice::write(const QByteArray &byteArray)
1691
Writes the content of \a byteArray to the device. Returns the number of
1692
bytes that were actually written, or -1 if an error occurred.
1694
\sa read(), writeData()
1698
Puts the character \a c back into the device, and decrements the
1699
current position unless the position is 0. This function is
1700
usually called to "undo" a getChar() operation, such as when
1701
writing a backtracking parser.
1703
If \a c was not previously read from the device, the behavior is
1706
\note This function is not available while a transaction is in progress.
1708
void QIODevice::ungetChar(char c)
1711
CHECK_READABLE(read, Q_VOID);
1713
if (d->transactionStarted) {
1714
checkWarnMessage(this, "ungetChar", "Called while transaction is in progress");
1718
#if defined QIODEVICE_DEBUG
1719
printf("%p QIODevice::ungetChar(0x%hhx '%c')\n", this, c, isprint(c) ? c : '?');
1722
d->buffer.ungetChar(c);
1723
if (!d->isSequential())
1727
/*! \fn bool QIODevice::putChar(char c)
1729
Writes the character \a c to the device. Returns \c true on success;
1730
otherwise returns \c false.
1732
\sa write(), getChar(), ungetChar()
1734
bool QIODevice::putChar(char c)
1736
return d_func()->putCharHelper(c);
1742
bool QIODevicePrivate::putCharHelper(char c)
1744
return q_func()->write(&c, 1) == 1;
1750
qint64 QIODevicePrivate::peek(char *data, qint64 maxSize)
1754
if (transactionStarted) {
1755
const qint64 savedTransactionPos = transactionPos;
1756
const qint64 savedPos = pos;
1758
qint64 readBytes = q->read(data, maxSize);
1760
// Restore initial position
1762
transactionPos = savedTransactionPos;
1764
seekBuffer(savedPos);
1768
q->startTransaction();
1769
qint64 readBytes = q->read(data, maxSize);
1770
q->rollbackTransaction();
1778
QByteArray QIODevicePrivate::peek(qint64 maxSize)
1782
if (transactionStarted) {
1783
const qint64 savedTransactionPos = transactionPos;
1784
const qint64 savedPos = pos;
1786
QByteArray result = q->read(maxSize);
1788
// Restore initial position
1790
transactionPos = savedTransactionPos;
1792
seekBuffer(savedPos);
1796
q->startTransaction();
1797
QByteArray result = q->read(maxSize);
1798
q->rollbackTransaction();
1803
/*! \fn bool QIODevice::getChar(char *c)
1805
Reads one character from the device and stores it in \a c. If \a c
1806
is 0, the character is discarded. Returns \c true on success;
1807
otherwise returns \c false.
1809
\sa read(), putChar(), ungetChar()
1811
bool QIODevice::getChar(char *c)
1813
// readability checked in read()
1815
return (1 == read(c ? c : &ch, 1));
1821
Reads at most \a maxSize bytes from the device into \a data, without side
1822
effects (i.e., if you call read() after peek(), you will get the same
1823
data). Returns the number of bytes read. If an error occurs, such as
1824
when attempting to peek a device opened in WriteOnly mode, this function
1827
0 is returned when no more data is available for reading.
1831
\snippet code/src_corelib_io_qiodevice.cpp 4
1835
qint64 QIODevice::peek(char *data, qint64 maxSize)
1837
return d_func()->peek(data, maxSize);
1844
Peeks at most \a maxSize bytes from the device, returning the data peeked
1849
\snippet code/src_corelib_io_qiodevice.cpp 5
1851
This function has no way of reporting errors; returning an empty
1852
QByteArray can mean either that no data was currently available
1853
for peeking, or that an error occurred.
1857
QByteArray QIODevice::peek(qint64 maxSize)
1859
return d_func()->peek(maxSize);
1863
Blocks until new data is available for reading and the readyRead()
1864
signal has been emitted, or until \a msecs milliseconds have
1865
passed. If msecs is -1, this function will not time out.
1867
Returns \c true if new data is available for reading; otherwise returns
1868
false (if the operation timed out or if an error occurred).
1870
This function can operate without an event loop. It is
1871
useful when writing non-GUI applications and when performing
1872
I/O operations in a non-GUI thread.
1874
If called from within a slot connected to the readyRead() signal,
1875
readyRead() will not be reemitted.
1877
Reimplement this function to provide a blocking API for a custom
1878
device. The default implementation does nothing, and returns \c false.
1880
\warning Calling this function from the main (GUI) thread
1881
might cause your user interface to freeze.
1883
\sa waitForBytesWritten()
1885
bool QIODevice::waitForReadyRead(int msecs)
1892
For buffered devices, this function waits until a payload of
1893
buffered written data has been written to the device and the
1894
bytesWritten() signal has been emitted, or until \a msecs
1895
milliseconds have passed. If msecs is -1, this function will
1896
not time out. For unbuffered devices, it returns immediately.
1898
Returns \c true if a payload of data was written to the device;
1899
otherwise returns \c false (i.e. if the operation timed out, or if an
1902
This function can operate without an event loop. It is
1903
useful when writing non-GUI applications and when performing
1904
I/O operations in a non-GUI thread.
1906
If called from within a slot connected to the bytesWritten() signal,
1907
bytesWritten() will not be reemitted.
1909
Reimplement this function to provide a blocking API for a custom
1910
device. The default implementation does nothing, and returns \c false.
1912
\warning Calling this function from the main (GUI) thread
1913
might cause your user interface to freeze.
1915
\sa waitForReadyRead()
1917
bool QIODevice::waitForBytesWritten(int msecs)
1924
Sets the human readable description of the last device error that
1929
void QIODevice::setErrorString(const QString &str)
1931
d_func()->errorString = str;
1935
Returns a human-readable description of the last device error that
1938
\sa setErrorString()
1940
QString QIODevice::errorString() const
1942
Q_D(const QIODevice);
1943
if (d->errorString.isEmpty()) {
1944
#ifdef QT_NO_QOBJECT
1945
return QLatin1String(QT_TRANSLATE_NOOP(QIODevice, "Unknown error"));
1947
return tr("Unknown error");
1950
return d->errorString;
1954
\fn qint64 QIODevice::readData(char *data, qint64 maxSize)
1956
Reads up to \a maxSize bytes from the device into \a data, and
1957
returns the number of bytes read or -1 if an error occurred.
1959
If there are no bytes to be read and there can never be more bytes
1960
available (examples include socket closed, pipe closed, sub-process
1961
finished), this function returns -1.
1963
This function is called by QIODevice. Reimplement this function
1964
when creating a subclass of QIODevice.
1966
When reimplementing this function it is important that this function
1967
reads all the required data before returning. This is required in order
1968
for QDataStream to be able to operate on the class. QDataStream assumes
1969
all the requested information was read and therefore does not retry reading
1970
if there was a problem.
1972
This function might be called with a maxSize of 0, which can be used to
1973
perform post-reading operations.
1975
\sa read(), readLine(), writeData()
1979
\fn qint64 QIODevice::writeData(const char *data, qint64 maxSize)
1981
Writes up to \a maxSize bytes from \a data to the device. Returns
1982
the number of bytes written, or -1 if an error occurred.
1984
This function is called by QIODevice. Reimplement this function
1985
when creating a subclass of QIODevice.
1987
When reimplementing this function it is important that this function
1988
writes all the data available before returning. This is required in order
1989
for QDataStream to be able to operate on the class. QDataStream assumes
1990
all the information was written and therefore does not retry writing if
1991
there was a problem.
1998
\fn int qt_subtract_from_timeout(int timeout, int elapsed)
2000
Reduces the \a timeout by \a elapsed, taking into account that -1 is a
2001
special value for timeouts.
2004
int qt_subtract_from_timeout(int timeout, int elapsed)
2009
timeout = timeout - elapsed;
2010
return timeout < 0 ? 0 : timeout;
2014
#if !defined(QT_NO_DEBUG_STREAM)
2015
QDebug operator<<(QDebug debug, QIODevice::OpenMode modes)
2017
debug << "OpenMode(";
2018
QStringList modeList;
2019
if (modes == QIODevice::NotOpen) {
2020
modeList << QLatin1String("NotOpen");
2022
if (modes & QIODevice::ReadOnly)
2023
modeList << QLatin1String("ReadOnly");
2024
if (modes & QIODevice::WriteOnly)
2025
modeList << QLatin1String("WriteOnly");
2026
if (modes & QIODevice::Append)
2027
modeList << QLatin1String("Append");
2028
if (modes & QIODevice::Truncate)
2029
modeList << QLatin1String("Truncate");
2030
if (modes & QIODevice::Text)
2031
modeList << QLatin1String("Text");
2032
if (modes & QIODevice::Unbuffered)
2033
modeList << QLatin1String("Unbuffered");
2035
std::sort(modeList.begin(), modeList.end());
2036
debug << modeList.join(QLatin1Char('|'));