source: trunk/src/corelib/io/qiodevice.cpp@ 964

Last change on this file since 964 was 846, checked in by Dmitry A. Kuminov, 14 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

File size: 54.1 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtCore module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42//#define QIODEVICE_DEBUG
43
44#include "qbytearray.h"
45#include "qdebug.h"
46#include "qiodevice_p.h"
47#include "qfile.h"
48#include "qstringlist.h"
49#include <limits.h>
50
51#ifdef QIODEVICE_DEBUG
52# include <ctype.h>
53#endif
54
55QT_BEGIN_NAMESPACE
56
57#ifdef QIODEVICE_DEBUG
58void debugBinaryString(const QByteArray &input)
59{
60 QByteArray tmp;
61 int startOffset = 0;
62 for (int i = 0; i < input.size(); ++i) {
63 tmp += input[i];
64
65 if ((i % 16) == 15 || i == (input.size() - 1)) {
66 printf("\n%15d:", startOffset);
67 startOffset += tmp.size();
68
69 for (int j = 0; j < tmp.size(); ++j)
70 printf(" %02x", int(uchar(tmp[j])));
71 for (int j = tmp.size(); j < 16 + 1; ++j)
72 printf(" ");
73 for (int j = 0; j < tmp.size(); ++j)
74 printf("%c", isprint(int(uchar(tmp[j]))) ? tmp[j] : '.');
75 tmp.clear();
76 }
77 }
78 printf("\n\n");
79}
80
81void debugBinaryString(const char *data, qint64 maxlen)
82{
83 debugBinaryString(QByteArray(data, maxlen));
84}
85#endif
86
87#define Q_VOID
88
89#define CHECK_MAXLEN(function, returnType) \
90 do { \
91 if (maxSize < 0) { \
92 qWarning("QIODevice::"#function": Called with maxSize < 0"); \
93 return returnType; \
94 } \
95 } while (0)
96
97#define CHECK_WRITABLE(function, returnType) \
98 do { \
99 if ((d->openMode & WriteOnly) == 0) { \
100 if (d->openMode == NotOpen) \
101 return returnType; \
102 qWarning("QIODevice::"#function": ReadOnly device"); \
103 return returnType; \
104 } \
105 } while (0)
106
107#define CHECK_READABLE(function, returnType) \
108 do { \
109 if ((d->openMode & ReadOnly) == 0) { \
110 if (d->openMode == NotOpen) \
111 return returnType; \
112 qWarning("QIODevice::"#function": WriteOnly device"); \
113 return returnType; \
114 } \
115 } while (0)
116
117/*! \internal
118 */
119QIODevicePrivate::QIODevicePrivate()
120 : openMode(QIODevice::NotOpen), buffer(QIODEVICE_BUFFERSIZE),
121 pos(0), devicePos(0)
122 , pPos(&pos), pDevicePos(&devicePos)
123 , baseReadLineDataCalled(false)
124 , firstRead(true)
125 , accessMode(Unset)
126#ifdef QT_NO_QOBJECT
127 , q_ptr(0)
128#endif
129{
130}
131
132/*! \internal
133 */
134QIODevicePrivate::~QIODevicePrivate()
135{
136}
137
138/*!
139 \class QIODevice
140 \reentrant
141
142 \brief The QIODevice class is the base interface class of all I/O
143 devices in Qt.
144
145 \ingroup io
146
147 QIODevice provides both a common implementation and an abstract
148 interface for devices that support reading and writing of blocks
149 of data, such as QFile, QBuffer and QTcpSocket. QIODevice is
150 abstract and can not be instantiated, but it is common to use the
151 interface it defines to provide device-independent I/O features.
152 For example, Qt's XML classes operate on a QIODevice pointer,
153 allowing them to be used with various devices (such as files and
154 buffers).
155
156 Before accessing the device, open() must be called to set the
157 correct OpenMode (such as ReadOnly or ReadWrite). You can then
158 write to the device with write() or putChar(), and read by calling
159 either read(), readLine(), or readAll(). Call close() when you are
160 done with the device.
161
162 QIODevice distinguishes between two types of devices:
163 random-access devices and sequential devices.
164
165 \list
166 \o Random-access devices support seeking to arbitrary
167 positions using seek(). The current position in the file is
168 available by calling pos(). QFile and QBuffer are examples of
169 random-access devices.
170
171 \o Sequential devices don't support seeking to arbitrary
172 positions. The data must be read in one pass. The functions
173 pos() and size() don't work for sequential devices.
174 QTcpSocket and QProcess are examples of sequential devices.
175 \endlist
176
177 You can use isSequential() to determine the type of device.
178
179 QIODevice emits readyRead() when new data is available for
180 reading; for example, if new data has arrived on the network or if
181 additional data is appended to a file that you are reading
182 from. You can call bytesAvailable() to determine the number of
183 bytes that are currently available for reading. It's common to use
184 bytesAvailable() together with the readyRead() signal when
185 programming with asynchronous devices such as QTcpSocket, where
186 fragments of data can arrive at arbitrary points in
187 time. QIODevice emits the bytesWritten() signal every time a
188 payload of data has been written to the device. Use bytesToWrite()
189 to determine the current amount of data waiting to be written.
190
191 Certain subclasses of QIODevice, such as QTcpSocket and QProcess,
192 are asynchronous. This means that I/O functions such as write()
193 or read() always return immediately, while communication with the
194 device itself may happen when control goes back to the event loop.
195 QIODevice provides functions that allow you to force these
196 operations to be performed immediately, while blocking the
197 calling thread and without entering the event loop. This allows
198 QIODevice subclasses to be used without an event loop, or in
199 a separate thread:
200
201 \list
202 \o waitForReadyRead() - This function suspends operation in the
203 calling thread until new data is available for reading.
204
205 \o waitForBytesWritten() - This function suspends operation in the
206 calling thread until one payload of data has been written to the
207 device.
208
209 \o waitFor....() - Subclasses of QIODevice implement blocking
210 functions for device-specific operations. For example, QProcess
211 has a function called waitForStarted() which suspends operation in
212 the calling thread until the process has started.
213 \endlist
214
215 Calling these functions from the main, GUI thread, may cause your
216 user interface to freeze. Example:
217
218 \snippet doc/src/snippets/code/src_corelib_io_qiodevice.cpp 0
219
220 By subclassing QIODevice, you can provide the same interface to
221 your own I/O devices. Subclasses of QIODevice are only required to
222 implement the protected readData() and writeData() functions.
223 QIODevice uses these functions to implement all its convenience
224 functions, such as getChar(), readLine() and write(). QIODevice
225 also handles access control for you, so you can safely assume that
226 the device is opened in write mode if writeData() is called.
227
228 Some subclasses, such as QFile and QTcpSocket, are implemented
229 using a memory buffer for intermediate storing of data. This
230 reduces the number of required device accessing calls, which are
231 often very slow. Buffering makes functions like getChar() and
232 putChar() fast, as they can operate on the memory buffer instead
233 of directly on the device itself. Certain I/O operations, however,
234 don't work well with a buffer. For example, if several users open
235 the same device and read it character by character, they may end
236 up reading the same data when they meant to read a separate chunk
237 each. For this reason, QIODevice allows you to bypass any
238 buffering by passing the Unbuffered flag to open(). When
239 subclassing QIODevice, remember to bypass any buffer you may use
240 when the device is open in Unbuffered mode.
241
242 \sa QBuffer QFile QTcpSocket
243*/
244
245/*!
246 \typedef QIODevice::Offset
247 \compat
248
249 Use \c qint64 instead.
250*/
251
252/*!
253 \typedef QIODevice::Status
254 \compat
255
256 Use QIODevice::OpenMode instead, or see the documentation for
257 specific devices.
258*/
259
260/*!
261 \enum QIODevice::OpenModeFlag
262
263 This enum is used with open() to describe the mode in which a device
264 is opened. It is also returned by openMode().
265
266 \value NotOpen The device is not open.
267 \value ReadOnly The device is open for reading.
268 \value WriteOnly The device is open for writing.
269 \value ReadWrite The device is open for reading and writing.
270 \value Append The device is opened in append mode, so that all data is
271 written to the end of the file.
272 \value Truncate If possible, the device is truncated before it is opened.
273 All earlier contents of the device are lost.
274 \value Text When reading, the end-of-line terminators are
275 translated to '\n'. When writing, the end-of-line
276 terminators are translated to the local encoding, for
277 example '\r\n' for Win32.
278 \value Unbuffered Any buffer in the device is bypassed.
279
280 Certain flags, such as \c Unbuffered and \c Truncate, are
281 meaningless when used with some subclasses. Some of these
282 restrictions are implied by the type of device that is represented
283 by a subclass. In other cases, the restriction may be due to the
284 implementation, or may be imposed by the underlying platform; for
285 example, QTcpSocket does not support \c Unbuffered mode, and
286 limitations in the native API prevent QFile from supporting \c
287 Unbuffered on Windows.
288*/
289
290/*! \fn QIODevice::bytesWritten(qint64 bytes)
291
292 This signal is emitted every time a payload of data has been
293 written to the device. The \a bytes argument is set to the number
294 of bytes that were written in this payload.
295
296 bytesWritten() is not emitted recursively; if you reenter the event loop
297 or call waitForBytesWritten() inside a slot connected to the
298 bytesWritten() signal, the signal will not be reemitted (although
299 waitForBytesWritten() may still return true).
300
301 \sa readyRead()
302*/
303
304/*!
305 \fn QIODevice::readyRead()
306
307 This signal is emitted once every time new data is available for
308 reading from the device. It will only be emitted again once new
309 data is available, such as when a new payload of network data has
310 arrived on your network socket, or when a new block of data has
311 been appended to your device.
312
313 readyRead() is not emitted recursively; if you reenter the event loop or
314 call waitForReadyRead() inside a slot connected to the readyRead() signal,
315 the signal will not be reemitted (although waitForReadyRead() may still
316 return true).
317
318 Note for developers implementing classes derived from QIODevice:
319 you should always emit readyRead() when new data has arrived (do not
320 emit it only because there's data still to be read in your
321 buffers). Do not emit readyRead() in other conditions.
322
323 \sa bytesWritten()
324*/
325
326/*! \fn QIODevice::aboutToClose()
327
328 This signal is emitted when the device is about to close. Connect
329 this signal if you have operations that need to be performed
330 before the device closes (e.g., if you have data in a separate
331 buffer that needs to be written to the device).
332*/
333
334/*!
335 \fn QIODevice::readChannelFinished()
336 \since 4.4
337
338 This signal is emitted when the input (reading) stream is closed
339 in this device. It is emitted as soon as the closing is detected,
340 which means that there might still be data available for reading
341 with read().
342
343 \sa atEnd(), read()
344*/
345
346#ifdef QT_NO_QOBJECT
347QIODevice::QIODevice()
348 : d_ptr(new QIODevicePrivate)
349{
350 d_ptr->q_ptr = this;
351}
352
353/*! \internal
354*/
355QIODevice::QIODevice(QIODevicePrivate &dd)
356 : d_ptr(&dd)
357{
358 d_ptr->q_ptr = this;
359}
360#else
361
362/*!
363 Constructs a QIODevice object.
364*/
365
366QIODevice::QIODevice()
367 : QObject(*new QIODevicePrivate, 0)
368{
369#if defined QIODEVICE_DEBUG
370 QFile *file = qobject_cast<QFile *>(this);
371 printf("%p QIODevice::QIODevice(\"%s\") %s\n", this, metaObject()->className(),
372 qPrintable(file ? file->fileName() : QString()));
373#endif
374}
375
376/*!
377 Constructs a QIODevice object with the given \a parent.
378*/
379
380QIODevice::QIODevice(QObject *parent)
381 : QObject(*new QIODevicePrivate, parent)
382{
383#if defined QIODEVICE_DEBUG
384 printf("%p QIODevice::QIODevice(%p \"%s\")\n", this, parent, metaObject()->className());
385#endif
386}
387
388/*! \internal
389*/
390QIODevice::QIODevice(QIODevicePrivate &dd, QObject *parent)
391 : QObject(dd, parent)
392{
393}
394#endif
395
396
397/*!
398 The destructor is virtual, and QIODevice is an abstract base
399 class. This destructor does not call close(), but the subclass
400 destructor might. If you are in doubt, call close() before
401 destroying the QIODevice.
402*/
403QIODevice::~QIODevice()
404{
405#if defined QIODEVICE_DEBUG
406 printf("%p QIODevice::~QIODevice()\n", this);
407#endif
408}
409
410/*!
411 Returns true if this device is sequential; otherwise returns
412 false.
413
414 Sequential devices, as opposed to a random-access devices, have no
415 concept of a start, an end, a size, or a current position, and they
416 do not support seeking. You can only read from the device when it
417 reports that data is available. The most common example of a
418 sequential device is a network socket. On Unix, special files such
419 as /dev/zero and fifo pipes are sequential.
420
421 Regular files, on the other hand, do support random access. They
422 have both a size and a current position, and they also support
423 seeking backwards and forwards in the data stream. Regular files
424 are non-sequential.
425
426 \sa bytesAvailable()
427*/
428bool QIODevice::isSequential() const
429{
430 return false;
431}
432
433/*!
434 Returns the mode in which the device has been opened;
435 i.e. ReadOnly or WriteOnly.
436
437 \sa OpenMode
438*/
439QIODevice::OpenMode QIODevice::openMode() const
440{
441 return d_func()->openMode;
442}
443
444/*!
445 Sets the OpenMode of the device to \a openMode. Call this
446 function to set the open mode if the flags change after the device
447 has been opened.
448
449 \sa openMode() OpenMode
450*/
451void QIODevice::setOpenMode(OpenMode openMode)
452{
453 Q_D(QIODevice);
454#if defined QIODEVICE_DEBUG
455 printf("%p QIODevice::setOpenMode(0x%x)\n", this, int(openMode));
456#endif
457 d->openMode = openMode;
458 d->accessMode = QIODevicePrivate::Unset;
459 d->firstRead = true;
460 if (!isReadable())
461 d->buffer.clear();
462}
463
464/*!
465 If \a enabled is true, this function sets the \l Text flag on the device;
466 otherwise the \l Text flag is removed. This feature is useful for classes
467 that provide custom end-of-line handling on a QIODevice.
468
469 \sa open(), setOpenMode()
470 */
471void QIODevice::setTextModeEnabled(bool enabled)
472{
473 Q_D(QIODevice);
474 if (enabled)
475 d->openMode |= Text;
476 else
477 d->openMode &= ~Text;
478}
479
480/*!
481 Returns true if the \l Text flag is enabled; otherwise returns false.
482
483 \sa setTextModeEnabled()
484*/
485bool QIODevice::isTextModeEnabled() const
486{
487 return d_func()->openMode & Text;
488}
489
490/*!
491 Returns true if the device is open; otherwise returns false. A
492 device is open if it can be read from and/or written to. By
493 default, this function returns false if openMode() returns
494 \c NotOpen.
495
496 \sa openMode() OpenMode
497*/
498bool QIODevice::isOpen() const
499{
500 return d_func()->openMode != NotOpen;
501}
502
503/*!
504 Returns true if data can be read from the device; otherwise returns
505 false. Use bytesAvailable() to determine how many bytes can be read.
506
507 This is a convenience function which checks if the OpenMode of the
508 device contains the ReadOnly flag.
509
510 \sa openMode() OpenMode
511*/
512bool QIODevice::isReadable() const
513{
514 return (openMode() & ReadOnly) != 0;
515}
516
517/*!
518 Returns true if data can be written to the device; otherwise returns
519 false.
520
521 This is a convenience function which checks if the OpenMode of the
522 device contains the WriteOnly flag.
523
524 \sa openMode() OpenMode
525*/
526bool QIODevice::isWritable() const
527{
528 return (openMode() & WriteOnly) != 0;
529}
530
531/*!
532 Opens the device and sets its OpenMode to \a mode. Returns true if successful;
533 otherwise returns false. This function should be called from any
534 reimplementations of open() or other functions that open the device.
535
536 \sa openMode() OpenMode
537*/
538bool QIODevice::open(OpenMode mode)
539{
540 Q_D(QIODevice);
541 d->openMode = mode;
542 d->pos = (mode & Append) ? size() : qint64(0);
543 d->buffer.clear();
544 d->accessMode = QIODevicePrivate::Unset;
545 d->firstRead = true;
546#if defined QIODEVICE_DEBUG
547 printf("%p QIODevice::open(0x%x)\n", this, quint32(mode));
548#endif
549 return true;
550}
551
552/*!
553 First emits aboutToClose(), then closes the device and sets its
554 OpenMode to NotOpen. The error string is also reset.
555
556 \sa setOpenMode() OpenMode
557*/
558void QIODevice::close()
559{
560 Q_D(QIODevice);
561 if (d->openMode == NotOpen)
562 return;
563
564#if defined QIODEVICE_DEBUG
565 printf("%p QIODevice::close()\n", this);
566#endif
567
568#ifndef QT_NO_QOBJECT
569 emit aboutToClose();
570#endif
571 d->openMode = NotOpen;
572 d->errorString.clear();
573 d->pos = 0;
574 d->buffer.clear();
575 d->firstRead = true;
576}
577
578/*!
579 For random-access devices, this function returns the position that
580 data is written to or read from. For sequential devices or closed
581 devices, where there is no concept of a "current position", 0 is
582 returned.
583
584 The current read/write position of the device is maintained internally by
585 QIODevice, so reimplementing this function is not necessary. When
586 subclassing QIODevice, use QIODevice::seek() to notify QIODevice about
587 changes in the device position.
588
589 \sa isSequential(), seek()
590*/
591qint64 QIODevice::pos() const
592{
593 Q_D(const QIODevice);
594#if defined QIODEVICE_DEBUG
595 printf("%p QIODevice::pos() == %d\n", this, int(d->pos));
596#endif
597 return d->pos;
598}
599
600/*!
601 For open random-access devices, this function returns the size of the
602 device. For open sequential devices, bytesAvailable() is returned.
603
604 If the device is closed, the size returned will not reflect the actual
605 size of the device.
606
607 \sa isSequential(), pos()
608*/
609qint64 QIODevice::size() const
610{
611 return d_func()->isSequential() ? bytesAvailable() : qint64(0);
612}
613
614/*!
615 For random-access devices, this function sets the current position
616 to \a pos, returning true on success, or false if an error occurred.
617 For sequential devices, the default behavior is to do nothing and
618 return false.
619
620 When subclassing QIODevice, you must call QIODevice::seek() at the
621 start of your function to ensure integrity with QIODevice's
622 built-in buffer. The base implementation always returns true.
623
624 \sa pos(), isSequential()
625*/
626bool QIODevice::seek(qint64 pos)
627{
628 Q_D(QIODevice);
629 if (d->openMode == NotOpen) {
630 qWarning("QIODevice::seek: The device is not open");
631 return false;
632 }
633 if (pos < 0) {
634 qWarning("QIODevice::seek: Invalid pos: %d", int(pos));
635 return false;
636 }
637
638#if defined QIODEVICE_DEBUG
639 printf("%p QIODevice::seek(%d), before: d->pos = %d, d->buffer.size() = %d\n",
640 this, int(pos), int(d->pos), d->buffer.size());
641#endif
642
643 qint64 offset = pos - d->pos;
644 if (!d->isSequential()) {
645 d->pos = pos;
646 d->devicePos = pos;
647 }
648
649 if (offset < 0
650 || offset >= qint64(d->buffer.size()))
651 // When seeking backwards, an operation that is only allowed for
652 // random-access devices, the buffer is cleared. The next read
653 // operation will then refill the buffer. We can optimize this, if we
654 // find that seeking backwards becomes a significant performance hit.
655 d->buffer.clear();
656 else if (!d->buffer.isEmpty())
657 d->buffer.skip(int(offset));
658
659#if defined QIODEVICE_DEBUG
660 printf("%p \tafter: d->pos == %d, d->buffer.size() == %d\n", this, int(d->pos),
661 d->buffer.size());
662#endif
663 return true;
664}
665
666/*!
667 Returns true if the current read and write position is at the end
668 of the device (i.e. there is no more data available for reading on
669 the device); otherwise returns false.
670
671 For some devices, atEnd() can return true even though there is more data
672 to read. This special case only applies to devices that generate data in
673 direct response to you calling read() (e.g., \c /dev or \c /proc files on
674 Unix and Mac OS X, or console input / \c stdin on all platforms).
675
676 \sa bytesAvailable(), read(), isSequential()
677*/
678bool QIODevice::atEnd() const
679{
680 Q_D(const QIODevice);
681#if defined QIODEVICE_DEBUG
682 printf("%p QIODevice::atEnd() returns %s, d->openMode == %d, d->pos == %d\n", this, (d->openMode == NotOpen || d->pos == size()) ? "true" : "false",
683 int(d->openMode), int(d->pos));
684#endif
685 return d->openMode == NotOpen || (d->buffer.isEmpty() && bytesAvailable() == 0);
686}
687
688/*!
689 Seeks to the start of input for random-access devices. Returns
690 true on success; otherwise returns false (for example, if the
691 device is not open).
692
693 Note that when using a QTextStream on a QFile, calling reset() on
694 the QFile will not have the expected result because QTextStream
695 buffers the file. Use the QTextStream::seek() function instead.
696
697 \sa seek()
698*/
699bool QIODevice::reset()
700{
701#if defined QIODEVICE_DEBUG
702 printf("%p QIODevice::reset()\n", this);
703#endif
704 return seek(0);
705}
706
707/*!
708 Returns the number of bytes that are available for reading. This
709 function is commonly used with sequential devices to determine the
710 number of bytes to allocate in a buffer before reading.
711
712 Subclasses that reimplement this function must call the base
713 implementation in order to include the size of QIODevices' buffer. Example:
714
715 \snippet doc/src/snippets/code/src_corelib_io_qiodevice.cpp 1
716
717 \sa bytesToWrite(), readyRead(), isSequential()
718*/
719qint64 QIODevice::bytesAvailable() const
720{
721 Q_D(const QIODevice);
722 if (!d->isSequential())
723 return qMax(size() - d->pos, qint64(0));
724 return d->buffer.size();
725}
726
727/*!
728 For buffered devices, this function returns the number of bytes
729 waiting to be written. For devices with no buffer, this function
730 returns 0.
731
732 \sa bytesAvailable(), bytesWritten(), isSequential()
733*/
734qint64 QIODevice::bytesToWrite() const
735{
736 return qint64(0);
737}
738
739#ifdef Q_CC_RVCT
740// arm mode makes the 64-bit integer operations much faster in RVCT 2.2
741#pragma push
742#pragma arm
743#endif
744
745/*!
746 Reads at most \a maxSize bytes from the device into \a data, and
747 returns the number of bytes read. If an error occurs, such as when
748 attempting to read from a device opened in WriteOnly mode, this
749 function returns -1.
750
751 0 is returned when no more data is available for reading. However,
752 reading past the end of the stream is considered an error, so this
753 function returns -1 in those cases (that is, reading on a closed
754 socket or after a process has died).
755
756 \sa readData() readLine() write()
757*/
758qint64 QIODevice::read(char *data, qint64 maxSize)
759{
760 Q_D(QIODevice);
761
762#if defined QIODEVICE_DEBUG
763 printf("%p QIODevice::read(%p, %d), d->pos = %d, d->buffer.size() = %d\n",
764 this, data, int(maxSize), int(d->pos), int(d->buffer.size()));
765#endif
766
767 // Short circuit for getChar()
768 if (maxSize == 1) {
769 int chint;
770 while ((chint = d->buffer.getChar()) != -1) {
771 ++(*d->pPos);
772
773 char c = char(uchar(chint));
774 if (c == '\r' && (d->openMode & Text))
775 continue;
776 *data = c;
777#if defined QIODEVICE_DEBUG
778 printf("%p \tread 0x%hhx (%c) returning 1 (shortcut)\n", this,
779 int(c), isprint(c) ? c : '?');
780#endif
781 return qint64(1);
782 }
783 }
784
785 CHECK_MAXLEN(read, qint64(-1));
786 qint64 readSoFar = 0;
787 bool moreToRead = true;
788 do {
789 // Try reading from the buffer.
790 int lastReadChunkSize = d->buffer.read(data, maxSize);
791 if (lastReadChunkSize > 0) {
792 *d->pPos += lastReadChunkSize;
793 readSoFar += lastReadChunkSize;
794 // fast exit when satisfied by buffer
795 if (lastReadChunkSize == maxSize && !(d->openMode & Text))
796 return readSoFar;
797
798 data += lastReadChunkSize;
799 maxSize -= lastReadChunkSize;
800#if defined QIODEVICE_DEBUG
801 printf("%p \treading %d bytes from buffer into position %d\n", this, lastReadChunkSize,
802 int(readSoFar) - lastReadChunkSize);
803#endif
804 } else {
805 if (d->firstRead) {
806 // this is the first time the file has been read, check it's valid and set up pos pointers
807 // for fast pos updates.
808 CHECK_READABLE(read, qint64(-1));
809 d->firstRead = false;
810 if (d->isSequential()) {
811 d->pPos = &d->seqDumpPos;
812 d->pDevicePos = &d->seqDumpPos;
813 }
814 }
815
816 if (!maxSize)
817 return readSoFar;
818
819 if ((d->openMode & Unbuffered) == 0 && maxSize < QIODEVICE_BUFFERSIZE) {
820 // In buffered mode, we try to fill up the QIODevice buffer before
821 // we do anything else.
822 // buffer is empty at this point, try to fill it
823 int bytesToBuffer = QIODEVICE_BUFFERSIZE;
824 char *writePointer = d->buffer.reserve(bytesToBuffer);
825
826 // Make sure the device is positioned correctly.
827 if (d->pos != d->devicePos && !d->isSequential() && !seek(d->pos))
828 return readSoFar ? readSoFar : qint64(-1);
829 qint64 readFromDevice = readData(writePointer, bytesToBuffer);
830 d->buffer.chop(bytesToBuffer - (readFromDevice < 0 ? 0 : int(readFromDevice)));
831
832 if (readFromDevice > 0) {
833 *d->pDevicePos += readFromDevice;
834#if defined QIODEVICE_DEBUG
835 printf("%p \treading %d from device into buffer\n", this, int(readFromDevice));
836#endif
837
838 if (!d->buffer.isEmpty()) {
839 lastReadChunkSize = d->buffer.read(data, maxSize);
840 readSoFar += lastReadChunkSize;
841 data += lastReadChunkSize;
842 maxSize -= lastReadChunkSize;
843 *d->pPos += lastReadChunkSize;
844#if defined QIODEVICE_DEBUG
845 printf("%p \treading %d bytes from buffer at position %d\n", this,
846 lastReadChunkSize, int(readSoFar));
847#endif
848 }
849 }
850 }
851 }
852
853 // If we need more, try reading from the device.
854 if (maxSize > 0) {
855 // Make sure the device is positioned correctly.
856 if (d->pos != d->devicePos && !d->isSequential() && !seek(d->pos))
857 return readSoFar ? readSoFar : qint64(-1);
858 qint64 readFromDevice = readData(data, maxSize);
859#if defined QIODEVICE_DEBUG
860 printf("%p \treading %d bytes from device (total %d)\n", this, int(readFromDevice), int(readSoFar));
861#endif
862 if (readFromDevice == -1 && readSoFar == 0) {
863 // error and we haven't read anything: return immediately
864 return -1;
865 }
866 if (readFromDevice > 0) {
867 lastReadChunkSize += int(readFromDevice);
868 readSoFar += readFromDevice;
869 data += readFromDevice;
870 maxSize -= readFromDevice;
871 *d->pPos += readFromDevice;
872 *d->pDevicePos += readFromDevice;
873 }
874 }
875 // Best attempt has been made to read data, don't try again except for text mode adjustment below
876 moreToRead = false;
877
878 if (readSoFar && d->openMode & Text) {
879 char *readPtr = data - lastReadChunkSize;
880 const char *endPtr = data;
881
882 if (readPtr < endPtr) {
883 // optimization to avoid initial self-assignment
884 while (*readPtr != '\r') {
885 if (++readPtr == endPtr)
886 return readSoFar;
887 }
888
889 char *writePtr = readPtr;
890
891 while (readPtr < endPtr) {
892 char ch = *readPtr++;
893 if (ch != '\r')
894 *writePtr++ = ch;
895 else {
896 --readSoFar;
897 --data;
898 ++maxSize;
899 }
900 }
901
902 // Make sure we get more data if there is room for more. This
903 // is very important for when someone seeks to the start of a
904 // '\r\n' and reads one character - they should get the '\n'.
905 moreToRead = (readPtr != writePtr);
906 }
907 }
908 } while (moreToRead);
909
910#if defined QIODEVICE_DEBUG
911 printf("%p \treturning %d, d->pos == %d, d->buffer.size() == %d\n", this,
912 int(readSoFar), int(d->pos), d->buffer.size());
913 debugBinaryString(data - readSoFar, readSoFar);
914#endif
915 return readSoFar;
916}
917
918#ifdef Q_CC_RVCT
919#pragma pop
920#endif
921
922/*!
923 \overload
924
925 Reads at most \a maxSize bytes from the device, and returns the
926 data read as a QByteArray.
927
928 This function has no way of reporting errors; returning an empty
929 QByteArray() can mean either that no data was currently available
930 for reading, or that an error occurred.
931*/
932QByteArray QIODevice::read(qint64 maxSize)
933{
934 Q_D(QIODevice);
935 QByteArray result;
936
937 CHECK_MAXLEN(read, result);
938
939#if defined QIODEVICE_DEBUG
940 printf("%p QIODevice::read(%d), d->pos = %d, d->buffer.size() = %d\n",
941 this, int(maxSize), int(d->pos), int(d->buffer.size()));
942#else
943 Q_UNUSED(d);
944#endif
945
946 if (maxSize != qint64(int(maxSize))) {
947 qWarning("QIODevice::read: maxSize argument exceeds QByteArray size limit");
948 maxSize = INT_MAX;
949 }
950
951 qint64 readBytes = 0;
952 if (maxSize) {
953 result.resize(int(maxSize));
954 if (!result.size()) {
955 // If resize fails, read incrementally.
956 qint64 readResult;
957 do {
958 result.resize(int(qMin(maxSize, result.size() + QIODEVICE_BUFFERSIZE)));
959 readResult = read(result.data() + readBytes, result.size() - readBytes);
960 if (readResult > 0 || readBytes == 0)
961 readBytes += readResult;
962 } while (readResult == QIODEVICE_BUFFERSIZE);
963 } else {
964 readBytes = read(result.data(), result.size());
965 }
966 }
967
968 if (readBytes <= 0)
969 result.clear();
970 else
971 result.resize(int(readBytes));
972
973 return result;
974}
975
976/*!
977 \overload
978
979 Reads all available data from the device, and returns it as a
980 QByteArray.
981
982 This function has no way of reporting errors; returning an empty
983 QByteArray() can mean either that no data was currently available
984 for reading, or that an error occurred.
985*/
986QByteArray QIODevice::readAll()
987{
988 Q_D(QIODevice);
989#if defined QIODEVICE_DEBUG
990 printf("%p QIODevice::readAll(), d->pos = %d, d->buffer.size() = %d\n",
991 this, int(d->pos), int(d->buffer.size()));
992#endif
993
994 QByteArray result;
995 qint64 readBytes = 0;
996
997 // flush internal read buffer
998 if (!(d->openMode & Text) && !d->buffer.isEmpty()) {
999 result = d->buffer.readAll();
1000 readBytes = result.size();
1001 d->pos += readBytes;
1002 }
1003
1004 qint64 theSize;
1005 if (d->isSequential() || (theSize = size()) == 0) {
1006 // Size is unknown, read incrementally.
1007 qint64 readResult;
1008 do {
1009 result.resize(result.size() + QIODEVICE_BUFFERSIZE);
1010 readResult = read(result.data() + readBytes, result.size() - readBytes);
1011 if (readResult > 0 || readBytes == 0)
1012 readBytes += readResult;
1013 } while (readResult > 0);
1014 } else {
1015 // Read it all in one go.
1016 // If resize fails, don't read anything.
1017 result.resize(int(readBytes + theSize - d->pos));
1018 readBytes += read(result.data() + readBytes, result.size() - readBytes);
1019 }
1020
1021 if (readBytes <= 0)
1022 result.clear();
1023 else
1024 result.resize(int(readBytes));
1025
1026 return result;
1027}
1028
1029#ifdef Q_CC_RVCT
1030// arm mode makes the 64-bit integer operations much faster in RVCT 2.2
1031#pragma push
1032#pragma arm
1033#endif
1034
1035/*!
1036 This function reads a line of ASCII characters from the device, up
1037 to a maximum of \a maxSize - 1 bytes, stores the characters in \a
1038 data, and returns the number of bytes read. If a line could not be
1039 read but no error ocurred, this function returns 0. If an error
1040 occurs, this function returns the length of what could be read, or
1041 -1 if nothing was read.
1042
1043 A terminating '\0' byte is always appended to \a data, so \a
1044 maxSize must be larger than 1.
1045
1046 Data is read until either of the following conditions are met:
1047
1048 \list
1049 \o The first '\n' character is read.
1050 \o \a maxSize - 1 bytes are read.
1051 \o The end of the device data is detected.
1052 \endlist
1053
1054 For example, the following code reads a line of characters from a
1055 file:
1056
1057 \snippet doc/src/snippets/code/src_corelib_io_qiodevice.cpp 2
1058
1059 The newline character ('\n') is included in the buffer. If a
1060 newline is not encountered before maxSize - 1 bytes are read, a
1061 newline will not be inserted into the buffer. On windows newline
1062 characters are replaced with '\n'.
1063
1064 This function calls readLineData(), which is implemented using
1065 repeated calls to getChar(). You can provide a more efficient
1066 implementation by reimplementing readLineData() in your own
1067 subclass.
1068
1069 \sa getChar(), read(), write()
1070*/
1071qint64 QIODevice::readLine(char *data, qint64 maxSize)
1072{
1073 Q_D(QIODevice);
1074 if (maxSize < 2) {
1075 qWarning("QIODevice::readLine: Called with maxSize < 2");
1076 return qint64(-1);
1077 }
1078
1079#if defined QIODEVICE_DEBUG
1080 printf("%p QIODevice::readLine(%p, %d), d->pos = %d, d->buffer.size() = %d\n",
1081 this, data, int(maxSize), int(d->pos), int(d->buffer.size()));
1082#endif
1083
1084 // Leave room for a '\0'
1085 --maxSize;
1086
1087 const bool sequential = d->isSequential();
1088
1089 qint64 readSoFar = 0;
1090 if (!d->buffer.isEmpty()) {
1091 readSoFar = d->buffer.readLine(data, maxSize);
1092 if (!sequential)
1093 d->pos += readSoFar;
1094#if defined QIODEVICE_DEBUG
1095 printf("%p \tread from buffer: %d bytes, last character read: %hhx\n", this,
1096 int(readSoFar), data[int(readSoFar) - 1]);
1097 if (readSoFar)
1098 debugBinaryString(data, int(readSoFar));
1099#endif
1100#if defined(Q_OS_SYMBIAN)
1101 // Open C fgets strips '\r' but readSoFar gets returned as if it was still there
1102 if ((d->openMode & Text) &&
1103 readSoFar > 1 &&
1104 data[readSoFar - 1] == '\0' &&
1105 data[readSoFar - 2] == '\n') {
1106 --readSoFar;
1107 }
1108#endif
1109 if (readSoFar && data[readSoFar - 1] == '\n') {
1110 if (d->openMode & Text) {
1111 // QRingBuffer::readLine() isn't Text aware.
1112 if (readSoFar > 1 && data[readSoFar - 2] == '\r') {
1113 --readSoFar;
1114 data[readSoFar - 1] = '\n';
1115 }
1116 }
1117 data[readSoFar] = '\0';
1118 return readSoFar;
1119 }
1120 }
1121
1122 if (d->pos != d->devicePos && !sequential && !seek(d->pos))
1123 return qint64(-1);
1124 d->baseReadLineDataCalled = false;
1125 qint64 readBytes = readLineData(data + readSoFar, maxSize - readSoFar);
1126#if defined QIODEVICE_DEBUG
1127 printf("%p \tread from readLineData: %d bytes, readSoFar = %d bytes\n", this,
1128 int(readBytes), int(readSoFar));
1129 if (readBytes > 0) {
1130 debugBinaryString(data, int(readSoFar + readBytes));
1131 }
1132#endif
1133 if (readBytes < 0) {
1134 data[readSoFar] = '\0';
1135 return readSoFar ? readSoFar : -1;
1136 }
1137 readSoFar += readBytes;
1138 if (!d->baseReadLineDataCalled && !sequential) {
1139 d->pos += readBytes;
1140 // If the base implementation was not called, then we must
1141 // assume the device position is invalid and force a seek.
1142 d->devicePos = qint64(-1);
1143 }
1144 data[readSoFar] = '\0';
1145
1146 if (d->openMode & Text) {
1147#if defined(Q_OS_SYMBIAN)
1148 // Open C fgets strips '\r' but readSoFar gets returned as if it was still there
1149 if (readSoFar > 1 && data[readSoFar - 1] == '\0' && data[readSoFar - 2] == '\n') {
1150 --readSoFar;
1151 }
1152#endif
1153 if (readSoFar > 1 && data[readSoFar - 1] == '\n' && data[readSoFar - 2] == '\r') {
1154 data[readSoFar - 2] = '\n';
1155 data[readSoFar - 1] = '\0';
1156 --readSoFar;
1157 }
1158 }
1159
1160#if defined QIODEVICE_DEBUG
1161 printf("%p \treturning %d, d->pos = %d, d->buffer.size() = %d, size() = %d\n",
1162 this, int(readSoFar), int(d->pos), d->buffer.size(), int(size()));
1163 debugBinaryString(data, int(readSoFar));
1164#endif
1165 return readSoFar;
1166}
1167
1168/*!
1169 \overload
1170
1171 Reads a line from the device, but no more than \a maxSize characters,
1172 and returns the result as a QByteArray.
1173
1174 This function has no way of reporting errors; returning an empty
1175 QByteArray() can mean either that no data was currently available
1176 for reading, or that an error occurred.
1177*/
1178QByteArray QIODevice::readLine(qint64 maxSize)
1179{
1180 Q_D(QIODevice);
1181 QByteArray result;
1182
1183 CHECK_MAXLEN(readLine, result);
1184
1185#if defined QIODEVICE_DEBUG
1186 printf("%p QIODevice::readLine(%d), d->pos = %d, d->buffer.size() = %d\n",
1187 this, int(maxSize), int(d->pos), int(d->buffer.size()));
1188#else
1189 Q_UNUSED(d);
1190#endif
1191
1192 if (maxSize > INT_MAX) {
1193 qWarning("QIODevice::read: maxSize argument exceeds QByteArray size limit");
1194 maxSize = INT_MAX;
1195 }
1196
1197 result.resize(int(maxSize));
1198 qint64 readBytes = 0;
1199 if (!result.size()) {
1200 // If resize fails or maxSize == 0, read incrementally
1201 if (maxSize == 0)
1202 maxSize = INT_MAX;
1203
1204 // The first iteration needs to leave an extra byte for the terminating null
1205 result.resize(1);
1206
1207 qint64 readResult;
1208 do {
1209 result.resize(int(qMin(maxSize, result.size() + QIODEVICE_BUFFERSIZE)));
1210 readResult = readLine(result.data() + readBytes, result.size() - readBytes);
1211 if (readResult > 0 || readBytes == 0)
1212 readBytes += readResult;
1213 } while (readResult == QIODEVICE_BUFFERSIZE
1214 && result[int(readBytes - 1)] != '\n');
1215 } else
1216 readBytes = readLine(result.data(), result.size());
1217
1218 if (readBytes <= 0)
1219 result.clear();
1220 else
1221 result.resize(readBytes);
1222
1223 return result;
1224}
1225
1226/*!
1227 Reads up to \a maxSize characters into \a data and returns the
1228 number of characters read.
1229
1230 This function is called by readLine(), and provides its base
1231 implementation, using getChar(). Buffered devices can improve the
1232 performance of readLine() by reimplementing this function.
1233
1234 readLine() appends a '\0' byte to \a data; readLineData() does not
1235 need to do this.
1236
1237 If you reimplement this function, be careful to return the correct
1238 value: it should return the number of bytes read in this line,
1239 including the terminating newline, or 0 if there is no line to be
1240 read at this point. If an error occurs, it should return -1 if and
1241 only if no bytes were read. Reading past EOF is considered an error.
1242*/
1243qint64 QIODevice::readLineData(char *data, qint64 maxSize)
1244{
1245 Q_D(QIODevice);
1246 qint64 readSoFar = 0;
1247 char c;
1248 int lastReadReturn = 0;
1249 d->baseReadLineDataCalled = true;
1250
1251 while (readSoFar < maxSize && (lastReadReturn = read(&c, 1)) == 1) {
1252 *data++ = c;
1253 ++readSoFar;
1254 if (c == '\n')
1255 break;
1256 }
1257
1258#if defined QIODEVICE_DEBUG
1259 printf("%p QIODevice::readLineData(%p, %d), d->pos = %d, d->buffer.size() = %d, returns %d\n",
1260 this, data, int(maxSize), int(d->pos), int(d->buffer.size()), int(readSoFar));
1261#endif
1262 if (lastReadReturn != 1 && readSoFar == 0)
1263 return isSequential() ? lastReadReturn : -1;
1264 return readSoFar;
1265}
1266
1267#ifdef Q_CC_RVCT
1268#pragma pop
1269#endif
1270
1271/*!
1272 Returns true if a complete line of data can be read from the device;
1273 otherwise returns false.
1274
1275 Note that unbuffered devices, which have no way of determining what
1276 can be read, always return false.
1277
1278 This function is often called in conjunction with the readyRead()
1279 signal.
1280
1281 Subclasses that reimplement this function must call the base
1282 implementation in order to include the contents of the QIODevice's buffer. Example:
1283
1284 \snippet doc/src/snippets/code/src_corelib_io_qiodevice.cpp 3
1285
1286 \sa readyRead(), readLine()
1287*/
1288bool QIODevice::canReadLine() const
1289{
1290 return d_func()->buffer.canReadLine();
1291}
1292
1293/*!
1294 Writes at most \a maxSize bytes of data from \a data to the
1295 device. Returns the number of bytes that were actually written, or
1296 -1 if an error occurred.
1297
1298 \sa read() writeData()
1299*/
1300qint64 QIODevice::write(const char *data, qint64 maxSize)
1301{
1302 Q_D(QIODevice);
1303 CHECK_WRITABLE(write, qint64(-1));
1304 CHECK_MAXLEN(write, qint64(-1));
1305
1306 const bool sequential = d->isSequential();
1307 // Make sure the device is positioned correctly.
1308 if (d->pos != d->devicePos && !sequential && !seek(d->pos))
1309 return qint64(-1);
1310
1311#if defined(Q_OS_WIN) || defined(Q_OS_OS2)
1312 if (d->openMode & Text) {
1313 const char *endOfData = data + maxSize;
1314 const char *startOfBlock = data;
1315
1316 qint64 writtenSoFar = 0;
1317
1318 forever {
1319 const char *endOfBlock = startOfBlock;
1320 while (endOfBlock < endOfData && *endOfBlock != '\n')
1321 ++endOfBlock;
1322
1323 qint64 blockSize = endOfBlock - startOfBlock;
1324 if (blockSize > 0) {
1325 qint64 ret = writeData(startOfBlock, blockSize);
1326 if (ret <= 0) {
1327 if (writtenSoFar && !sequential)
1328 d->buffer.skip(writtenSoFar);
1329 return writtenSoFar ? writtenSoFar : ret;
1330 }
1331 if (!sequential) {
1332 d->pos += ret;
1333 d->devicePos += ret;
1334 }
1335 writtenSoFar += ret;
1336 }
1337
1338 if (endOfBlock == endOfData)
1339 break;
1340
1341 qint64 ret = writeData("\r\n", 2);
1342 if (ret <= 0) {
1343 if (writtenSoFar && !sequential)
1344 d->buffer.skip(writtenSoFar);
1345 return writtenSoFar ? writtenSoFar : ret;
1346 }
1347 if (!sequential) {
1348 d->pos += ret;
1349 d->devicePos += ret;
1350 }
1351 ++writtenSoFar;
1352
1353 startOfBlock = endOfBlock + 1;
1354 }
1355
1356 if (writtenSoFar && !sequential)
1357 d->buffer.skip(writtenSoFar);
1358 return writtenSoFar;
1359 }
1360#endif
1361
1362 qint64 written = writeData(data, maxSize);
1363 if (written > 0) {
1364 if (!sequential) {
1365 d->pos += written;
1366 d->devicePos += written;
1367 }
1368 if (!d->buffer.isEmpty() && !sequential)
1369 d->buffer.skip(written);
1370 }
1371 return written;
1372}
1373
1374/*!
1375 \since 4.5
1376
1377 \overload
1378
1379 Writes data from a zero-terminated string of 8-bit characters to the
1380 device. Returns the number of bytes that were actually written, or
1381 -1 if an error occurred. This is equivalent to
1382 \code
1383 ...
1384 QIODevice::write(data, qstrlen(data));
1385 ...
1386 \endcode
1387
1388 \sa read() writeData()
1389*/
1390qint64 QIODevice::write(const char *data)
1391{
1392 return write(data, qstrlen(data));
1393}
1394
1395/*! \fn qint64 QIODevice::write(const QByteArray &byteArray)
1396
1397 \overload
1398
1399 Writes the content of \a byteArray to the device. Returns the number of
1400 bytes that were actually written, or -1 if an error occurred.
1401
1402 \sa read() writeData()
1403*/
1404
1405/*!
1406 Puts the character \a c back into the device, and decrements the
1407 current position unless the position is 0. This function is
1408 usually called to "undo" a getChar() operation, such as when
1409 writing a backtracking parser.
1410
1411 If \a c was not previously read from the device, the behavior is
1412 undefined.
1413*/
1414void QIODevice::ungetChar(char c)
1415{
1416 Q_D(QIODevice);
1417 CHECK_READABLE(read, Q_VOID);
1418
1419#if defined QIODEVICE_DEBUG
1420 printf("%p QIODevice::ungetChar(0x%hhx '%c')\n", this, c, isprint(c) ? c : '?');
1421#endif
1422
1423 d->buffer.ungetChar(c);
1424 if (!d->isSequential())
1425 --d->pos;
1426}
1427
1428/*! \fn bool QIODevice::putChar(char c)
1429
1430 Writes the character \a c to the device. Returns true on success;
1431 otherwise returns false.
1432
1433 \sa write() getChar() ungetChar()
1434*/
1435bool QIODevice::putChar(char c)
1436{
1437 return d_func()->putCharHelper(c);
1438}
1439
1440/*!
1441 \internal
1442*/
1443bool QIODevicePrivate::putCharHelper(char c)
1444{
1445 return q_func()->write(&c, 1) == 1;
1446}
1447
1448/*!
1449 \internal
1450*/
1451qint64 QIODevicePrivate::peek(char *data, qint64 maxSize)
1452{
1453 qint64 readBytes = q_func()->read(data, maxSize);
1454 if (readBytes <= 0)
1455 return readBytes;
1456
1457 buffer.ungetBlock(data, readBytes);
1458 *pPos -= readBytes;
1459 return readBytes;
1460}
1461
1462/*!
1463 \internal
1464*/
1465QByteArray QIODevicePrivate::peek(qint64 maxSize)
1466{
1467 QByteArray result = q_func()->read(maxSize);
1468
1469 if (result.isEmpty())
1470 return result;
1471
1472 buffer.ungetBlock(result.constData(), result.size());
1473 *pPos -= result.size();
1474 return result;
1475}
1476
1477/*! \fn bool QIODevice::getChar(char *c)
1478
1479 Reads one character from the device and stores it in \a c. If \a c
1480 is 0, the character is discarded. Returns true on success;
1481 otherwise returns false.
1482
1483 \sa read() putChar() ungetChar()
1484*/
1485bool QIODevice::getChar(char *c)
1486{
1487 // readability checked in read()
1488 char ch;
1489 return (1 == read(c ? c : &ch, 1));
1490}
1491
1492/*!
1493 \since 4.1
1494
1495 Reads at most \a maxSize bytes from the device into \a data, without side
1496 effects (i.e., if you call read() after peek(), you will get the same
1497 data). Returns the number of bytes read. If an error occurs, such as
1498 when attempting to peek a device opened in WriteOnly mode, this function
1499 returns -1.
1500
1501 0 is returned when no more data is available for reading.
1502
1503 Example:
1504
1505 \snippet doc/src/snippets/code/src_corelib_io_qiodevice.cpp 4
1506
1507 \sa read()
1508*/
1509qint64 QIODevice::peek(char *data, qint64 maxSize)
1510{
1511 return d_func()->peek(data, maxSize);
1512}
1513
1514/*!
1515 \since 4.1
1516 \overload
1517
1518 Peeks at most \a maxSize bytes from the device, returning the data peeked
1519 as a QByteArray.
1520
1521 Example:
1522
1523 \snippet doc/src/snippets/code/src_corelib_io_qiodevice.cpp 5
1524
1525 This function has no way of reporting errors; returning an empty
1526 QByteArray() can mean either that no data was currently available
1527 for peeking, or that an error occurred.
1528
1529 \sa read()
1530*/
1531QByteArray QIODevice::peek(qint64 maxSize)
1532{
1533 return d_func()->peek(maxSize);
1534}
1535
1536/*!
1537 Blocks until new data is available for reading and the readyRead()
1538 signal has been emitted, or until \a msecs milliseconds have
1539 passed. If msecs is -1, this function will not time out.
1540
1541 Returns true if new data is available for reading; otherwise returns
1542 false (if the operation timed out or if an error occurred).
1543
1544 This function can operate without an event loop. It is
1545 useful when writing non-GUI applications and when performing
1546 I/O operations in a non-GUI thread.
1547
1548 If called from within a slot connected to the readyRead() signal,
1549 readyRead() will not be reemitted.
1550
1551 Reimplement this function to provide a blocking API for a custom
1552 device. The default implementation does nothing, and returns false.
1553
1554 \warning Calling this function from the main (GUI) thread
1555 might cause your user interface to freeze.
1556
1557 \sa waitForBytesWritten()
1558*/
1559bool QIODevice::waitForReadyRead(int msecs)
1560{
1561 Q_UNUSED(msecs);
1562 return false;
1563}
1564
1565/*!
1566 For buffered devices, this function waits until a payload of
1567 buffered written data has been written to the device and the
1568 bytesWritten() signal has been emitted, or until \a msecs
1569 milliseconds have passed. If msecs is -1, this function will
1570 not time out. For unbuffered devices, it returns immediately.
1571
1572 Returns true if a payload of data was written to the device;
1573 otherwise returns false (i.e. if the operation timed out, or if an
1574 error occurred).
1575
1576 This function can operate without an event loop. It is
1577 useful when writing non-GUI applications and when performing
1578 I/O operations in a non-GUI thread.
1579
1580 If called from within a slot connected to the bytesWritten() signal,
1581 bytesWritten() will not be reemitted.
1582
1583 Reimplement this function to provide a blocking API for a custom
1584 device. The default implementation does nothing, and returns false.
1585
1586 \warning Calling this function from the main (GUI) thread
1587 might cause your user interface to freeze.
1588
1589 \sa waitForReadyRead()
1590*/
1591bool QIODevice::waitForBytesWritten(int msecs)
1592{
1593 Q_UNUSED(msecs);
1594 return false;
1595}
1596
1597/*!
1598 Sets the human readable description of the last device error that
1599 occurred to \a str.
1600
1601 \sa errorString()
1602*/
1603void QIODevice::setErrorString(const QString &str)
1604{
1605 d_func()->errorString = str;
1606}
1607
1608/*!
1609 Returns a human-readable description of the last device error that
1610 occurred.
1611
1612 \sa setErrorString()
1613*/
1614QString QIODevice::errorString() const
1615{
1616 Q_D(const QIODevice);
1617 if (d->errorString.isEmpty()) {
1618#ifdef QT_NO_QOBJECT
1619 return QLatin1String(QT_TRANSLATE_NOOP(QIODevice, "Unknown error"));
1620#else
1621 return tr("Unknown error");
1622#endif
1623 }
1624 return d->errorString;
1625}
1626
1627/*!
1628 \fn qint64 QIODevice::readData(char *data, qint64 maxSize)
1629
1630 Reads up to \a maxSize bytes from the device into \a data, and
1631 returns the number of bytes read or -1 if an error occurred. If
1632 there are no bytes to be read, this function should return -1 if
1633 there can never be more bytes available (for example: socket
1634 closed, pipe closed, sub-process finished).
1635
1636 This function is called by QIODevice. Reimplement this function
1637 when creating a subclass of QIODevice.
1638
1639 \sa read() readLine() writeData()
1640*/
1641
1642/*!
1643 \fn qint64 QIODevice::writeData(const char *data, qint64 maxSize)
1644
1645 Writes up to \a maxSize bytes from \a data to the device. Returns
1646 the number of bytes written, or -1 if an error occurred.
1647
1648 This function is called by QIODevice. Reimplement this function
1649 when creating a subclass of QIODevice.
1650
1651 \sa read() write()
1652*/
1653
1654/*!
1655 \fn QIODevice::Offset QIODevice::status() const
1656
1657 For device specific error handling, please refer to the
1658 individual device documentation.
1659
1660 \sa qobject_cast()
1661*/
1662
1663/*!
1664 \fn QIODevice::Offset QIODevice::at() const
1665
1666 Use pos() instead.
1667*/
1668
1669/*!
1670 \fn bool QIODevice::at(Offset offset)
1671
1672 Use seek(\a offset) instead.
1673*/
1674
1675/*! \fn int QIODevice::flags() const
1676
1677 Use openMode() instead.
1678*/
1679
1680/*! \fn int QIODevice::getch()
1681
1682 Use getChar() instead.
1683*/
1684
1685/*!
1686 \fn bool QIODevice::isAsynchronous() const
1687
1688 This functionality is no longer available. This function always
1689 returns true.
1690*/
1691
1692/*!
1693 \fn bool QIODevice::isBuffered() const
1694
1695 Use !(openMode() & QIODevice::Unbuffered) instead.
1696*/
1697
1698/*!
1699 \fn bool QIODevice::isCombinedAccess() const
1700
1701 Use openMode() instead.
1702*/
1703
1704/*!
1705 \fn bool QIODevice::isDirectAccess() const
1706
1707 Use !isSequential() instead.
1708*/
1709
1710/*!
1711 \fn bool QIODevice::isInactive() const
1712
1713 Use isOpen(), isReadable(), or isWritable() instead.
1714*/
1715
1716/*!
1717 \fn bool QIODevice::isRaw() const
1718
1719 Use openMode() instead.
1720*/
1721
1722/*!
1723 \fn bool QIODevice::isSequentialAccess() const
1724
1725 Use isSequential() instead.
1726*/
1727
1728/*!
1729 \fn bool QIODevice::isSynchronous() const
1730
1731 This functionality is no longer available. This function always
1732 returns false.
1733*/
1734
1735/*!
1736 \fn bool QIODevice::isTranslated() const
1737
1738 Use openMode() instead.
1739*/
1740
1741/*!
1742 \fn bool QIODevice::mode() const
1743
1744 Use openMode() instead.
1745*/
1746
1747/*! \fn int QIODevice::putch(int ch)
1748
1749 Use putChar(\a ch) instead.
1750*/
1751
1752/*! \fn int QIODevice::ungetch(int ch)
1753
1754 Use ungetChar(\a ch) instead.
1755*/
1756
1757/*!
1758 \fn quint64 QIODevice::readBlock(char *data, quint64 size)
1759
1760 Use read(\a data, \a size) instead.
1761*/
1762
1763/*! \fn int QIODevice::state() const
1764
1765 Use isOpen() instead.
1766*/
1767
1768/*!
1769 \fn qint64 QIODevice::writeBlock(const char *data, quint64 size)
1770
1771 Use write(\a data, \a size) instead.
1772*/
1773
1774/*!
1775 \fn qint64 QIODevice::writeBlock(const QByteArray &data)
1776
1777 Use write(\a data) instead.
1778*/
1779
1780#if defined QT3_SUPPORT
1781QIODevice::Status QIODevice::status() const
1782{
1783#if !defined(QT_NO_QOBJECT)
1784 const QFile *f = qobject_cast<const QFile *>(this);
1785 if (f) return (int) f->error();
1786#endif
1787 return isOpen() ? 0 /* IO_Ok */ : 8 /* IO_UnspecifiedError */;
1788}
1789
1790/*!
1791 For device specific error handling, please refer to the
1792 individual device documentation.
1793
1794 \sa qobject_cast()
1795*/
1796void QIODevice::resetStatus()
1797{
1798#if !defined(QT_NO_QOBJECT)
1799 QFile *f = qobject_cast<QFile *>(this);
1800 if (f) f->unsetError();
1801#endif
1802}
1803#endif
1804
1805#if !defined(QT_NO_DEBUG_STREAM)
1806QDebug operator<<(QDebug debug, QIODevice::OpenMode modes)
1807{
1808 debug << "OpenMode(";
1809 QStringList modeList;
1810 if (modes == QIODevice::NotOpen) {
1811 modeList << QLatin1String("NotOpen");
1812 } else {
1813 if (modes & QIODevice::ReadOnly)
1814 modeList << QLatin1String("ReadOnly");
1815 if (modes & QIODevice::WriteOnly)
1816 modeList << QLatin1String("WriteOnly");
1817 if (modes & QIODevice::Append)
1818 modeList << QLatin1String("Append");
1819 if (modes & QIODevice::Truncate)
1820 modeList << QLatin1String("Truncate");
1821 if (modes & QIODevice::Text)
1822 modeList << QLatin1String("Text");
1823 if (modes & QIODevice::Unbuffered)
1824 modeList << QLatin1String("Unbuffered");
1825 }
1826 qSort(modeList);
1827 debug << modeList.join(QLatin1String("|"));
1828 debug << ')';
1829 return debug;
1830}
1831#endif
1832
1833QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.