~oif-team/ubuntu/natty/qt4-x11/xi2.1

« back to all changes in this revision

Viewing changes to src/corelib/io/qiodevice.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Adam Conrad
  • Date: 2005-08-24 04:09:09 UTC
  • Revision ID: james.westby@ubuntu.com-20050824040909-xmxe9jfr4a0w5671
Tags: upstream-4.0.0
ImportĀ upstreamĀ versionĀ 4.0.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/****************************************************************************
 
2
**
 
3
** Copyright (C) 1992-2005 Trolltech AS. All rights reserved.
 
4
**
 
5
** This file is part of the core module of the Qt Toolkit.
 
6
**
 
7
** This file may be distributed under the terms of the Q Public License
 
8
** as defined by Trolltech AS of Norway and appearing in the file
 
9
** LICENSE.QPL included in the packaging of this file.
 
10
**
 
11
** This file may be distributed and/or modified under the terms of the
 
12
** GNU General Public License version 2 as published by the Free Software
 
13
** Foundation and appearing in the file LICENSE.GPL included in the
 
14
** packaging of this file.
 
15
**
 
16
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
 
17
**   information about Qt Commercial License Agreements.
 
18
** See http://www.trolltech.com/qpl/ for QPL licensing information.
 
19
** See http://www.trolltech.com/gpl/ for GPL licensing information.
 
20
**
 
21
** Contact info@trolltech.com if any conditions of this licensing are
 
22
** not clear to you.
 
23
**
 
24
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 
25
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 
26
**
 
27
****************************************************************************/
 
28
 
 
29
#include "qbytearray.h"
 
30
#include "qiodevice_p.h"
 
31
#include "qfile.h"
 
32
 
 
33
#define Q_VOID
 
34
 
 
35
#define CHECK_OPEN(function, returnType) \
 
36
    do { \
 
37
        if (!isOpen()) { \
 
38
            return returnType; \
 
39
        } \
 
40
    } while (0)
 
41
 
 
42
#define CHECK_MAXLEN(function, returnType) \
 
43
    do { \
 
44
        if (maxSize < 0) { \
 
45
            qWarning("QIODevice::"#function" called with maxSize < 0"); \
 
46
            return returnType; \
 
47
        } \
 
48
    } while (0)
 
49
 
 
50
#define CHECK_WRITABLE(function, returnType) \
 
51
   do { \
 
52
       if ((d->openMode & WriteOnly) == 0) { \
 
53
           qWarning("QIODevice::"#function" called on a ReadOnly device"); \
 
54
           return returnType; \
 
55
       } \
 
56
   } while (0)
 
57
 
 
58
#define CHECK_READABLE(function, returnType) \
 
59
   do { \
 
60
       if ((d->openMode & ReadOnly) == 0) { \
 
61
           qWarning("QIODevice::"#function" called on a WriteOnly device"); \
 
62
           return returnType; \
 
63
       } \
 
64
   } while (0)
 
65
 
 
66
/*! \internal
 
67
 */
 
68
QIODevicePrivate::QIODevicePrivate()
 
69
{
 
70
    openMode = QIODevice::NotOpen;
 
71
    errorString = QT_TRANSLATE_NOOP(QIODevice, QLatin1String("Unknown error"));
 
72
}
 
73
 
 
74
/*! \internal
 
75
 */
 
76
QIODevicePrivate::~QIODevicePrivate()
 
77
{
 
78
}
 
79
 
 
80
/*!
 
81
    \class QIODevice
 
82
    \reentrant
 
83
 
 
84
    \brief The QIODevice class is the base interface class of all I/O
 
85
    devices in Qt.
 
86
 
 
87
    \ingroup io
 
88
 
 
89
    QIODevice provides both a common implementation and an abstract
 
90
    interface for devices that support reading and writing of blocks
 
91
    of data, such as QFile, QBuffer and QTcpSocket. QIODevice is
 
92
    abstract and can not be instantiated, but is it common to use the
 
93
    interface it defines to provide device-independent I/O features.
 
94
    For example, Qt's XML classes operate on a QIODevice pointer,
 
95
    allowing them to be used with various devices (such as files and
 
96
    buffers).
 
97
 
 
98
    Before accessing the device, open() must be called to set the
 
99
    correct OpenMode (such as ReadOnly or ReadWrite). You can then
 
100
    write to the device with write() or putChar(), and read by calling
 
101
    either read(), readLine(), or readAll(). Call close() when you are
 
102
    done with the device.
 
103
 
 
104
    QIODevice distinguishes between two types of devices:
 
105
    random-access devices and sequential devices.
 
106
 
 
107
    \list
 
108
    \o Random-access devices support seeking to arbitrary
 
109
    positions using seek(). The current position in the file is
 
110
    available by calling pos(). QFile and QBuffer are examples of
 
111
    random-access devices.
 
112
 
 
113
    \o Sequential devices don't support seeking to arbitrary
 
114
    positions. The data must be read in one pass. Functions
 
115
    like pos(), seek(), and size() don't work for sequential
 
116
    devices. QTcpSocket and QProcess are examples of sequential
 
117
    devices.
 
118
    \endlist
 
119
 
 
120
    You can use isSequential() to determine the type of device.
 
121
 
 
122
    QIODevice emits readyRead() when new data is available for
 
123
    reading; for example, if new data has arrived on the network or if
 
124
    additional data is appended to a file that you are reading
 
125
    from. You can call bytesAvailable() to determine the number of
 
126
    bytes that currently available for reading. It's common to use
 
127
    bytesAvailable() together with the readyRead() signal when
 
128
    programming with asynchronous devices such as QTcpSocket, where
 
129
    fragments of data can arrive at arbitrary points in
 
130
    time. QIODevice emits the bytesWritten() signal every time a
 
131
    payload of data has been written to the device. Use bytesToWrite()
 
132
    to determine the current amount of data waiting to be written.
 
133
 
 
134
    Certain subclasses of QIODevice, such as QTcpSocket and QProcess,
 
135
    are asynchronous. This means that I/O functions such as write()
 
136
    or read() always return immediately, while communication with the
 
137
    device itself may happen when control goes back to the event loop.
 
138
    QIODevice provides functions that allow you to force these
 
139
    operations to be performed immediately, while blocking the
 
140
    calling thread and without entering the event loop. This allows
 
141
    QIODevice subclasses to be used without an event loop, or in
 
142
    a separate thread:
 
143
 
 
144
    \list
 
145
    \o waitForReadyRead() - This function suspends operation in the
 
146
    calling thread until new data is available for reading.
 
147
 
 
148
    \o waitForBytesWritten() - This function suspends operation in the
 
149
    calling thread until one payload of data has been written to the
 
150
    device.
 
151
 
 
152
    \o waitFor....() - Subclasses of QIODevice implement blocking
 
153
    functions for device-specific operations. For example, QProcess
 
154
    has a function called waitForStarted() which suspends operation in
 
155
    the calling thread until the process has started.
 
156
    \endlist
 
157
 
 
158
    Calling these functions from the main, GUI thread, may cause your
 
159
    user interface to freeze. Example:
 
160
 
 
161
    \code
 
162
        QProcess gzip;
 
163
        gzip.start("gzip", QStringList() << "-c");
 
164
        if (!gzip.waitForStarted())
 
165
            return false;
 
166
 
 
167
        gzip.write("uncompressed data");
 
168
 
 
169
        QByteArray compressed;
 
170
        while (gzip.waitForReadyRead())
 
171
            compressed += gzip.readAll();
 
172
    \endcode
 
173
 
 
174
    By subclassing QIODevice, you can provide the same interface to
 
175
    your own I/O devices. Subclasses of QIODevice are only required to
 
176
    implement the protected readData() and writeData() functions.
 
177
    QIODevice uses these functions to implement all its convenience
 
178
    functions, such as getChar(), readLine() and write(). QIODevice
 
179
    also handles access control for you, so you can safely assume that
 
180
    the device is opened in write mode if writeData() is called.
 
181
 
 
182
    Some subclasses, such as QFile and QTcpSocket, are implemented
 
183
    using a memory buffer for intermediate storing of data. This
 
184
    reduces the number of required device accessing calls, which are
 
185
    often very slow. Buffering makes functions like getChar() and
 
186
    putChar() fast, as they can operate on the memory buffer instead
 
187
    of directly on the device itself. Certain I/O operations, however,
 
188
    don't work well with a buffer. For example, if several users open
 
189
    the same device and read it character by character, they may end
 
190
    up reading the same data when they meant to read a separate chunk
 
191
    each. For this reason, QIODevice allows you to bypass any
 
192
    buffering by passing the Unbuffered flag to open(). When
 
193
    subclassing QIODevice, remember to bypass any buffer you may use
 
194
    when the device is open in Unbuffered mode.
 
195
 
 
196
    \sa QBuffer QFile QTcpSocket
 
197
*/
 
198
 
 
199
/*!
 
200
    \enum QIODevice::Offset
 
201
    \compat
 
202
 
 
203
    Use \c qint64 instead.
 
204
*/
 
205
 
 
206
/*!
 
207
    \enum QIODevice::Status
 
208
    \compat
 
209
 
 
210
    Use QIODevice::OpenMode instead, or see the documentation for
 
211
    specific devices.
 
212
*/
 
213
 
 
214
/*!
 
215
    \enum QIODevice::OpenModeFlag
 
216
 
 
217
    This enum is used with open() to describe the mode in which a device
 
218
    is opened. It is also returned by openMode().
 
219
 
 
220
    \value NotOpen   The device is not open.
 
221
    \value ReadOnly  The device is open for reading.
 
222
    \value WriteOnly The device is open for writing.
 
223
    \value ReadWrite The device is open for reading and writing.
 
224
    \value Append    The device is opened in append mode, so that all data is
 
225
                     written to the end of the file.
 
226
    \value Truncate  If possible, the device is truncated before it is opened.
 
227
                     All earlier contents of the device are lost.
 
228
    \value Text When reading lines using readLine(), end-of-line
 
229
                     terminators are translated to the local encoding.
 
230
    \value Unbuffered Any buffer in the device is bypassed.
 
231
 
 
232
    Certain flags, such as QIODevice::Unbuffered and
 
233
    QIODevice::Truncate, might be meaningless for some subclasses.
 
234
    (For example, access to a QBuffer is always unbuffered.)
 
235
*/
 
236
 
 
237
/*!     \fn QIODevice::bytesWritten(qint64 bytes)
 
238
 
 
239
    This signal is emitted every time a payload of data has been
 
240
    written to the device. The \a bytes argument is set to the number
 
241
    of bytes that were written in this payload.
 
242
 
 
243
    bytesWritten() is not emitted recursively; if you reenter the event loop
 
244
    or call waitForBytesWritten() inside a slot connected to the
 
245
    bytesWritten() signal, the signal will not be reemitted (although
 
246
    waitForBytesWritten() may still return true).
 
247
 
 
248
    \sa readyRead()
 
249
*/
 
250
 
 
251
/*!     \fn QIODevice::readyRead()
 
252
 
 
253
    This signal is emitted once every time new data is available for
 
254
    reading from the device. It will only be emitted again once new
 
255
    data is available, such as when a new payload of network data has
 
256
    arrived on your network socket, or when a new block of data has
 
257
    been appended to your file.
 
258
 
 
259
    readyRead() is not emitted recursively; if you reenter the event loop or
 
260
    call waitForReadyRead() inside a slot connected to the readyRead() signal,
 
261
    the signal will not be reemitted (although waitForReadyRead() may still
 
262
    return true).
 
263
 
 
264
    \sa bytesWritten()
 
265
*/
 
266
 
 
267
/*! \fn QIODevice::aboutToClose()
 
268
 
 
269
    This signal is emitted when the device is about to close. Connect
 
270
    this signal if you have operations that need to be performed
 
271
    before the device closes (e.g., if you have data in a separate
 
272
    buffer that needs to be written to the device).
 
273
*/
 
274
 
 
275
#ifdef QT_NO_QOBJECT
 
276
QIODevice::QIODevice()
 
277
    : d_ptr(new QIODevicePrivate)
 
278
{
 
279
    d_ptr->q_ptr = this;
 
280
}
 
281
 
 
282
/*! \internal
 
283
*/
 
284
QIODevice::QIODevice(QIODevicePrivate &dd)
 
285
    : d_ptr(&dd)
 
286
{
 
287
    d_ptr->q_ptr = this;
 
288
}
 
289
#else
 
290
 
 
291
/*!
 
292
    Constructs a QIODevice object.
 
293
*/
 
294
 
 
295
QIODevice::QIODevice()
 
296
    : QObject(*new QIODevicePrivate, 0)
 
297
{
 
298
}
 
299
 
 
300
/*!
 
301
    Constructs a QIODevice object with the given \a parent.
 
302
*/
 
303
 
 
304
QIODevice::QIODevice(QObject *parent)
 
305
    : QObject(*new QIODevicePrivate, parent)
 
306
{
 
307
}
 
308
 
 
309
/*! \internal
 
310
*/
 
311
QIODevice::QIODevice(QIODevicePrivate &dd, QObject *parent)
 
312
    : QObject(dd, parent)
 
313
{
 
314
}
 
315
#endif
 
316
 
 
317
 
 
318
/*!
 
319
    Destructs the QIODevice object.
 
320
*/
 
321
QIODevice::~QIODevice()
 
322
{
 
323
}
 
324
 
 
325
/*!
 
326
    Returns true if this device is sequential; otherwise returns
 
327
    false.
 
328
 
 
329
    Sequential devices, as opposed to a random-access devices, have no
 
330
    concept of a start, an end, a size, or a current position, and they
 
331
    do not support seeking. You can only read from the device when it
 
332
    reports that data is available. The most common example of a
 
333
    sequential device is a network socket. On Unix, special files such
 
334
    as /dev/zero and fifo pipes are sequential.
 
335
 
 
336
    Regular files, on the other hand, do support random access. They
 
337
    have both a size and a current position, and they also support
 
338
    seeking backwards and forwards in the data stream. Regular files
 
339
    are non-sequential.
 
340
 
 
341
    \sa bytesAvailable()
 
342
*/
 
343
bool QIODevice::isSequential() const
 
344
{
 
345
    return false;
 
346
}
 
347
 
 
348
/*!
 
349
    Returns the mode in which the device has been opened;
 
350
    i.e. ReadOnly or WriteOnly.
 
351
 
 
352
    \sa OpenMode
 
353
*/
 
354
QIODevice::OpenMode QIODevice::openMode() const
 
355
{
 
356
    return d_func()->openMode;
 
357
}
 
358
 
 
359
/*!
 
360
    Sets the OpenMode of the device to \a openMode. Reimplement this
 
361
    function to set the open mode when reimplementing open().
 
362
 
 
363
    \sa openMode() OpenMode
 
364
*/
 
365
void QIODevice::setOpenMode(OpenMode openMode)
 
366
{
 
367
    d_func()->openMode = openMode;
 
368
}
 
369
 
 
370
/*!
 
371
    If \a enabled is true, this function sets the \l Text flag on the device;
 
372
    otherwise the \l Text flag is removed. This feature is useful for classes
 
373
    that provide custom end-of-line handling on a QIODevice.
 
374
 
 
375
    \sa open(), setOpenMode()
 
376
 */
 
377
void QIODevice::setTextModeEnabled(bool enabled)
 
378
{
 
379
    Q_D(QIODevice);
 
380
    if (enabled)
 
381
        d->openMode |= Text;
 
382
    else
 
383
        d->openMode &= ~Text;
 
384
}
 
385
 
 
386
/*!
 
387
    Returns true if the \l Text flag is enabled; otherwise returns false.
 
388
 
 
389
    \sa setTextModeEnabled()
 
390
*/
 
391
bool QIODevice::isTextModeEnabled() const
 
392
{
 
393
    return d_func()->openMode & Text;
 
394
}
 
395
 
 
396
/*!
 
397
    Returns true if the device is open; otherwise returns false. A
 
398
    device is open if it can be read from and/or written to. By
 
399
    default, this function returns false if openMode() returns
 
400
    \c NotOpen.
 
401
 
 
402
    \sa openMode() OpenMode
 
403
*/
 
404
bool QIODevice::isOpen() const
 
405
{
 
406
    return d_func()->openMode != NotOpen;
 
407
}
 
408
 
 
409
/*!
 
410
    Returns true if data can be read from the device; otherwise returns
 
411
    false. Use bytesAvailable() to determine how many bytes can be read.
 
412
 
 
413
    This is a convenience function which checks if the OpenMode of the
 
414
    device contains the ReadOnly flag.
 
415
 
 
416
    \sa openMode() OpenMode
 
417
*/
 
418
bool QIODevice::isReadable() const
 
419
{
 
420
    return (openMode() & ReadOnly) != 0;
 
421
}
 
422
 
 
423
/*!
 
424
    Returns true if data can be written to the device; otherwise returns
 
425
    false.
 
426
 
 
427
    This is a convenience function which checks if the OpenMode of the
 
428
    device contains the WriteOnly flag.
 
429
 
 
430
    \sa openMode() OpenMode
 
431
*/
 
432
bool QIODevice::isWritable() const
 
433
{
 
434
    return (openMode() & WriteOnly) != 0;
 
435
}
 
436
 
 
437
/*!
 
438
    Opens the device and sets its OpenMode to \a mode.
 
439
 
 
440
    \sa openMode() OpenMode
 
441
*/
 
442
bool QIODevice::open(OpenMode mode)
 
443
{
 
444
    d_func()->openMode = mode;
 
445
    return true;
 
446
}
 
447
 
 
448
/*!
 
449
    First emits aboutToClose(), then closes the device and sets its
 
450
    OpenMode to NotOpen. The error string is also reset.
 
451
 
 
452
    \sa setOpenMode() OpenMode
 
453
*/
 
454
void QIODevice::close()
 
455
{
 
456
    Q_D(QIODevice);
 
457
    if (d->openMode == NotOpen)
 
458
        return;
 
459
 
 
460
#ifndef QT_NO_QOBJECT
 
461
    emit aboutToClose();
 
462
#endif
 
463
    d->openMode = NotOpen;
 
464
#ifdef QT_NO_QOBJECT
 
465
    d->errorString = QT_TRANSLATE_NOOP(QIODevice, "Unknown error");
 
466
#else
 
467
    d->errorString = tr("Unknown error");
 
468
#endif
 
469
}
 
470
 
 
471
/*!
 
472
    For random-access devices, this function returns the position that
 
473
    data is written to or read from. For sequential devices or closed
 
474
    devices, where there is no concept of a "current position", 0 is
 
475
    returned.
 
476
 
 
477
    \sa isSequential(), seek()
 
478
*/
 
479
qint64 QIODevice::pos() const
 
480
{
 
481
    return qint64(0);
 
482
}
 
483
 
 
484
/*!
 
485
    For open random-access devices, this function returns the size of the
 
486
    device. For open sequential devices, bytesAvailable() is returned.
 
487
 
 
488
    If the device is closed, the size returned will not reflect the actual
 
489
    size of the device.
 
490
*/
 
491
qint64 QIODevice::size() const
 
492
{
 
493
    if (isSequential())
 
494
        return bytesAvailable();
 
495
    return 0;
 
496
}
 
497
 
 
498
/*!
 
499
    For random-access devices, this function sets the current position
 
500
    to \a pos, returning true on success, or false if an error occurred.
 
501
    For sequential devices, the default behavior is to do nothing and
 
502
    return false.
 
503
 
 
504
    When subclassing QIODevice, you must call QIODevice::seek() at the
 
505
    start of your function to ensure integrity with QIODevice's
 
506
    built-in ungetbuffer. The base implementation always returns true.
 
507
 
 
508
    \sa pos()
 
509
*/
 
510
bool QIODevice::seek(qint64 pos)
 
511
{
 
512
    Q_D(QIODevice);
 
513
    if (pos > 0)
 
514
        d->ungetBuffer.chop(pos);
 
515
    else
 
516
        d->ungetBuffer.clear();
 
517
    return true;
 
518
}
 
519
 
 
520
/*!
 
521
    Returns true if the current read and write position is at the end
 
522
    of the device (i.e. there is no more data available for reading on
 
523
    the device); otherwise returns false.
 
524
*/
 
525
bool QIODevice::atEnd() const
 
526
{
 
527
    return isOpen() && (pos() == size());
 
528
}
 
529
 
 
530
/*!
 
531
    Seeks to the start of input for random-access devices. Returns
 
532
    true on success; otherwise returns false (for example, if the
 
533
    device is not open).
 
534
 
 
535
    \sa seek()
 
536
*/
 
537
bool QIODevice::reset()
 
538
{
 
539
    return seek(0);
 
540
}
 
541
 
 
542
/*!
 
543
    Returns the number of bytes that are available for reading. This
 
544
    function is commonly used with sequential devices to determine the
 
545
    number of bytes to allocate in a buffer before reading.
 
546
*/
 
547
qint64 QIODevice::bytesAvailable() const
 
548
{
 
549
    if (!isSequential())
 
550
        return size() - pos();
 
551
    return 0;
 
552
}
 
553
 
 
554
/*!
 
555
    For buffered devices, this function returns the number of bytes
 
556
    waiting to be written. For devices with no buffer, this function
 
557
    returns 0.
 
558
*/
 
559
qint64 QIODevice::bytesToWrite() const
 
560
{
 
561
    return qint64(0);
 
562
}
 
563
 
 
564
/*!
 
565
    Reads at most \a maxSize bytes from the device into \a data, and
 
566
    returns the number of bytes read. If an error occurs, such as when
 
567
    attempting to read from a device opened in WriteOnly mode, this
 
568
    function returns -1.
 
569
 
 
570
    0 is returned when no more data is available for reading.
 
571
 
 
572
    \sa readData() readLine() write()
 
573
*/
 
574
qint64 QIODevice::read(char *data, qint64 maxSize)
 
575
{
 
576
    Q_D(QIODevice);
 
577
    CHECK_OPEN(read, qint64(-1));
 
578
    CHECK_READABLE(read, qint64(-1));
 
579
    CHECK_MAXLEN(read, qint64(-1));
 
580
    qint64 readSoFar = qint64(0);
 
581
 
 
582
    if (int ungetSize = d->ungetBuffer.size()) {
 
583
        do {
 
584
            if (readSoFar + 1 > maxSize) {
 
585
                d->ungetBuffer.resize(d->ungetBuffer.size() - readSoFar);
 
586
                return readSoFar;
 
587
            }
 
588
 
 
589
            data[readSoFar++] = d->ungetBuffer[ungetSize-- - 1];
 
590
        } while (ungetSize > 0);
 
591
        d->ungetBuffer.resize(d->ungetBuffer.size() - readSoFar);
 
592
    }
 
593
 
 
594
    qint64 ret = readData(data + readSoFar, maxSize - readSoFar);
 
595
    if (ret <= 0)
 
596
        return readSoFar ? readSoFar : ret;
 
597
 
 
598
    if (d->openMode & Text) {
 
599
        forever {
 
600
            char *readPtr = data + readSoFar;
 
601
            char *endPtr = readPtr + ret;
 
602
 
 
603
            // optimization to avoid initial self-assignment
 
604
            while (*readPtr != '\r') {
 
605
                if (++readPtr == endPtr)
 
606
                    return readSoFar + ret;
 
607
            }
 
608
 
 
609
            char *writePtr = readPtr;
 
610
 
 
611
            while (readPtr < endPtr) {
 
612
                char ch = *readPtr++;
 
613
                if (ch != '\r') {
 
614
                    *writePtr++ = ch;
 
615
                } else {
 
616
                    --ret;
 
617
                }
 
618
            }
 
619
 
 
620
            if (readPtr == writePtr)
 
621
                break;
 
622
 
 
623
            qint64 newRet = readData(writePtr, readPtr - writePtr);
 
624
            if (newRet <= 0)
 
625
                break;
 
626
 
 
627
            readSoFar += ret;
 
628
            ret = newRet;
 
629
        }
 
630
    }
 
631
 
 
632
    return readSoFar + ret;
 
633
}
 
634
 
 
635
/*!
 
636
    \overload
 
637
 
 
638
    Reads at most \a maxSize bytes from the device, and returns the
 
639
    data read as a QByteArray.
 
640
 
 
641
    This function has no way of reporting errors; returning an empty
 
642
    QByteArray() can mean either that no data was currently available
 
643
    for reading, or that an error occurred.
 
644
*/
 
645
QByteArray QIODevice::read(qint64 maxSize)
 
646
{
 
647
    CHECK_MAXLEN(read, QByteArray());
 
648
    QByteArray tmp;
 
649
    qint64 readSoFar = 0;
 
650
    char buffer[4096];
 
651
 
 
652
    do {
 
653
        qint64 bytesToRead = qMin(int(maxSize - readSoFar), int(sizeof(buffer)));
 
654
        qint64 readBytes = read(buffer, bytesToRead);
 
655
        if (readBytes <= 0)
 
656
            break;
 
657
        tmp += QByteArray(buffer, (int) readBytes);
 
658
        readSoFar += readBytes;
 
659
    } while (readSoFar < maxSize && bytesAvailable() > 0);
 
660
 
 
661
    return tmp;
 
662
}
 
663
 
 
664
/*!
 
665
    \overload
 
666
 
 
667
    Reads all available data from the device, and returns it as a
 
668
    QByteArray.
 
669
 
 
670
    This function has no way of reporting errors; returning an empty
 
671
    QByteArray() can mean either that no data was currently available
 
672
    for reading, or that an error occurred.
 
673
*/
 
674
QByteArray QIODevice::readAll()
 
675
{
 
676
    const int chunkSize = 4096;
 
677
    qint64 totalRead = 0;
 
678
    QByteArray tmp;
 
679
    forever {
 
680
        tmp.resize(tmp.size() + chunkSize);
 
681
        qint64 readBytes = read(tmp.data() + totalRead, chunkSize);
 
682
        if (readBytes < chunkSize) {
 
683
            tmp.chop(chunkSize - (readBytes < 0 ? qint64(0) : readBytes));
 
684
            return tmp;
 
685
        }
 
686
        totalRead += readBytes;
 
687
    }
 
688
    return tmp;
 
689
}
 
690
 
 
691
/*!
 
692
    This function reads a line of ASCII characters from the device, up
 
693
    to a maximum of \a maxSize bytes, stores the characters in \a data,
 
694
    and returns the number of bytes read. If an error occurred, -1 is
 
695
    returned.
 
696
 
 
697
    If there is room in the buffer (i.e. the line read is shorter than
 
698
    \a maxSize characters), a '\0' byte is appended to \a data.
 
699
 
 
700
    Data is read until either of the following conditions are met:
 
701
 
 
702
    \list
 
703
    \o The first '\n' character is read.
 
704
    \o \a maxSize bytes are read.
 
705
    \o The end of the device data is detected.
 
706
    \endlist
 
707
 
 
708
    For example, the following code reads a line of characters from a
 
709
    file:
 
710
 
 
711
    \code
 
712
        QFile file("box.txt");
 
713
        if (file.open(QFile::ReadOnly)) {
 
714
            char buf[1024];
 
715
            qint64 lineLength = file.readLine(buf, sizeof(buf));
 
716
            if (lineLength != -1) {
 
717
                // the line is available in buf
 
718
            }
 
719
        }
 
720
    \endcode
 
721
 
 
722
    If the '\n' character is the 1024th character read then it will be
 
723
    inserted into the buffer; if it occurs after the 1024 character then
 
724
    it is not read.
 
725
 
 
726
    This function calls readLineData(), which is implemented using
 
727
    repeated calls to getChar(). You can provide a more efficient
 
728
    implementation by reimplementing readLineData() in your own
 
729
    subclass.
 
730
 
 
731
    \sa getChar(), read(), write()
 
732
*/
 
733
qint64 QIODevice::readLine(char *data, qint64 maxSize)
 
734
{
 
735
    Q_D(QIODevice);
 
736
    if (maxSize < 1) {
 
737
        qWarning("QIODevice::readLine() called with maxSize < 1");
 
738
        return qint64(-1);
 
739
    }
 
740
 
 
741
    qint64 readSoFar = 0;
 
742
    if (int ungetSize = d->ungetBuffer.size()) {
 
743
        do {
 
744
            if (readSoFar + 1 > maxSize) {
 
745
                if (readSoFar < maxSize)
 
746
                    data[readSoFar] = '\0';
 
747
                d->ungetBuffer.resize(d->ungetBuffer.size() - readSoFar);
 
748
                return readSoFar;
 
749
            }
 
750
 
 
751
            char c = d->ungetBuffer[ungetSize-- - 1];
 
752
            data[readSoFar++] = c;
 
753
            if (c == '\n') {
 
754
                if (readSoFar < maxSize)
 
755
                    data[readSoFar] = '\0';
 
756
                return readSoFar;
 
757
            }
 
758
        } while (ungetSize > 0);
 
759
        d->ungetBuffer.resize(d->ungetBuffer.size() - readSoFar);
 
760
    }
 
761
 
 
762
    return readLineData(data + readSoFar, maxSize - readSoFar);
 
763
}
 
764
 
 
765
/*!
 
766
    \overload
 
767
 
 
768
    Reads a line from the device, but no more than \a maxSize characters,
 
769
    and returns the result as a QByteArray.
 
770
 
 
771
    This function has no way of reporting errors; returning an empty
 
772
    QByteArray() can mean either that no data was currently available
 
773
    for reading, or that an error occurred.
 
774
*/
 
775
QByteArray QIODevice::readLine(qint64 maxSize)
 
776
{
 
777
    CHECK_MAXLEN(readLine, QByteArray());
 
778
    QByteArray tmp;
 
779
    char buffer[4096];
 
780
    Q_UNUSED(buffer);
 
781
    qint64 readSoFar = 0;
 
782
    qint64 readBytes = 0;
 
783
 
 
784
    do {
 
785
        if (maxSize != 0)
 
786
            tmp.resize(readSoFar + qMin(int(maxSize), int(sizeof(buffer))));
 
787
        else
 
788
            tmp.resize(readSoFar + int(sizeof(buffer)));
 
789
        readBytes = readLineData(tmp.data() + readSoFar, tmp.size());
 
790
        readSoFar += readBytes;
 
791
    } while (readSoFar < maxSize && readBytes > 0
 
792
             && readBytes == tmp.size() && tmp.at(readBytes - 1) != '\n');
 
793
 
 
794
    tmp.resize(readSoFar);
 
795
    return tmp;
 
796
}
 
797
 
 
798
/*!
 
799
    Reads up to \a maxSize characters into \a data and returns the
 
800
    number of characters read.
 
801
 
 
802
    This function is called by readLine(), and provides its base
 
803
    implementation, using getChar(). Buffered devices can improve the
 
804
    performance of readLine() by reimplementing this function.
 
805
 
 
806
    When reimplementing this function, keep in mind that you must
 
807
    handle the \l Text flag which translates end-of-line characters.
 
808
*/
 
809
qint64 QIODevice::readLineData(char *data, qint64 maxSize)
 
810
{
 
811
    qint64 readSoFar = 0;
 
812
    char c;
 
813
    bool lastGetSucceeded = false;
 
814
    while (readSoFar + 1 < maxSize && (lastGetSucceeded = getChar(&c))) {
 
815
        *data++ = c;
 
816
        ++readSoFar;
 
817
        if (c == '\n')
 
818
            break;
 
819
    }
 
820
 
 
821
    if (readSoFar < maxSize)
 
822
        *data = '\0';
 
823
 
 
824
    if (!lastGetSucceeded && readSoFar == 0)
 
825
        return qint64(-1);
 
826
    return readSoFar;
 
827
}
 
828
 
 
829
/*!
 
830
    Returns true if a complete line of data can be read from the device;
 
831
    otherwise returns false.
 
832
 
 
833
    Note that unbuffered devices, which have no way of determining what
 
834
    can be read, always return false.
 
835
 
 
836
    This function is often called in conjunction with the readyRead()
 
837
    signal.
 
838
 
 
839
    \sa readyRead(), readLine()
 
840
*/
 
841
bool QIODevice::canReadLine() const
 
842
{
 
843
    return false;
 
844
}
 
845
 
 
846
/*! \fn bool QIODevice::getChar(char *c)
 
847
 
 
848
    Reads one character from the device and stores it in \a c. If \a c
 
849
    is 0, the character is discarded. Returns true on success;
 
850
    otherwise returns false.
 
851
 
 
852
    \sa read() putChar() ungetChar()
 
853
*/
 
854
 
 
855
/*!
 
856
    Writes at most \a maxSize bytes of data from \a data to the
 
857
    device. Returns the number of bytes that were actually written, or
 
858
    -1 if an error occurred.
 
859
 
 
860
    \sa read() writeData()
 
861
*/
 
862
qint64 QIODevice::write(const char *data, qint64 maxSize)
 
863
{
 
864
    Q_D(QIODevice);
 
865
    CHECK_OPEN(write, qint64(-1));
 
866
    CHECK_WRITABLE(write, qint64(-1));
 
867
    CHECK_MAXLEN(write, qint64(-1));
 
868
 
 
869
#ifdef Q_OS_WIN
 
870
    if (d->openMode & Text) {
 
871
        const char *endOfData = data + maxSize;
 
872
        const char *startOfBlock = data;
 
873
 
 
874
        qint64 writtenSoFar = 0;
 
875
 
 
876
        forever {
 
877
            const char *endOfBlock = startOfBlock;
 
878
            while (endOfBlock < endOfData && *endOfBlock != '\n')
 
879
                ++endOfBlock;
 
880
 
 
881
            qint64 blockSize = endOfBlock - startOfBlock;
 
882
            if (blockSize > 0) {
 
883
                qint64 ret = writeData(startOfBlock, blockSize);
 
884
                if (ret <= 0) {
 
885
                    if (writtenSoFar)
 
886
                        d->ungetBuffer.chop(writtenSoFar);
 
887
                    return writtenSoFar ? writtenSoFar : ret;
 
888
                }
 
889
                writtenSoFar += ret;
 
890
            }
 
891
 
 
892
            if (endOfBlock == endOfData)
 
893
                break;
 
894
 
 
895
            qint64 ret = writeData("\r\n", 2);
 
896
            if (ret <= 0) {
 
897
                if (writtenSoFar)
 
898
                    d->ungetBuffer.chop(writtenSoFar);
 
899
                return writtenSoFar ? writtenSoFar : ret;
 
900
            }
 
901
            ++writtenSoFar;
 
902
 
 
903
            startOfBlock = endOfBlock + 1;
 
904
        }
 
905
 
 
906
        if (writtenSoFar)
 
907
            d->ungetBuffer.chop(writtenSoFar);
 
908
        return writtenSoFar;
 
909
    }
 
910
#endif
 
911
    qint64 written = writeData(data, maxSize);
 
912
    d->ungetBuffer.chop(written);
 
913
    return written;
 
914
}
 
915
 
 
916
/*! \fn qint64 QIODevice::write(const QByteArray &byteArray)
 
917
 
 
918
    \overload
 
919
 
 
920
    Writes the content of \a byteArray to the device. Returns the number of
 
921
    bytes that were actually written, or -1 if an error occurred.
 
922
 
 
923
    \sa read() writeData()
 
924
*/
 
925
 
 
926
/*! \fn bool QIODevice::putChar(char c)
 
927
 
 
928
    Writes the character \a c to the device. Returns true on success;
 
929
    otherwise returns false.
 
930
 
 
931
    \sa write() getChar() ungetChar()
 
932
*/
 
933
 
 
934
/*!
 
935
    Puts the character \a c back into the device, and decrements the
 
936
    current position unless the position is 0. This function is
 
937
    usually called to "undo" a getChar() operation, such as when
 
938
    writing a backtracking parser.
 
939
 
 
940
    If \a c was not previously read from the device, the behavior is
 
941
    undefined.
 
942
*/
 
943
void QIODevice::ungetChar(char c)
 
944
{
 
945
    Q_D(QIODevice);
 
946
    CHECK_OPEN(write, Q_VOID);
 
947
    CHECK_READABLE(read, Q_VOID);
 
948
    d->ungetBuffer.append(c);
 
949
    if (!isSequential()) {
 
950
        qint64 curPos = pos();
 
951
        if (curPos > 0)
 
952
            seek(curPos - 1);
 
953
    }
 
954
}
 
955
 
 
956
/*!
 
957
    Blocks until data is available for reading and the readyRead()
 
958
    signal has been emitted, or until \a msecs milliseconds have
 
959
    passed. If msecs is -1, this function will not time out.
 
960
 
 
961
    Returns true if data is available for reading; otherwise returns
 
962
    false (if the operation timed out or if an error occurred).
 
963
 
 
964
    This function can operate without an event loop. It is
 
965
    useful when writing non-GUI applications and when performing
 
966
    I/O operations in a non-GUI thread.
 
967
 
 
968
    If called from within a slot connected to the readyRead() signal,
 
969
    readyRead() will not be reemitted.
 
970
    
 
971
    \warning Calling this function from the main (GUI) thread
 
972
    might cause your user interface to freeze.
 
973
 
 
974
    \sa waitForBytesWritten()
 
975
*/
 
976
bool QIODevice::waitForReadyRead(int msecs)
 
977
{
 
978
    Q_UNUSED(msecs);
 
979
    return false;
 
980
}
 
981
 
 
982
/*!
 
983
    For buffered devices, this function waits until a payload of
 
984
    buffered written data has been written to the device and the
 
985
    bytesWritten() signal has been emitted, or until \a msecs
 
986
    milliseconds have passed. If msecs is -1, this function will
 
987
    not time out. For unbuffered devices, it returns immediately.
 
988
 
 
989
    Returns true if a payload of data was written to the device;
 
990
    otherwise returns false (i.e. if the operation timed out, or if an
 
991
    error occurred).
 
992
 
 
993
    This function can operate without an event loop. It is
 
994
    useful when writing non-GUI applications and when performing
 
995
    I/O operations in a non-GUI thread.
 
996
 
 
997
    If called from within a slot connected to the bytesWritten() signal,
 
998
    bytesWritten() will not be reemitted.
 
999
 
 
1000
    \warning Calling this function from the main (GUI) thread
 
1001
    might cause your user interface to freeze.
 
1002
 
 
1003
    \sa waitForReadyRead()
 
1004
*/
 
1005
bool QIODevice::waitForBytesWritten(int msecs)
 
1006
{
 
1007
    Q_UNUSED(msecs);
 
1008
    return false;
 
1009
}
 
1010
 
 
1011
/*!
 
1012
    Sets the human readable description of the last device error that
 
1013
    occurred to \a str.
 
1014
 
 
1015
    \sa errorString()
 
1016
*/
 
1017
void QIODevice::setErrorString(const QString &str)
 
1018
{
 
1019
    d_func()->errorString = str;
 
1020
}
 
1021
 
 
1022
/*!
 
1023
    Returns a human-readable description of the last device error that
 
1024
    occurred.
 
1025
 
 
1026
    \sa setErrorString()
 
1027
*/
 
1028
QString QIODevice::errorString() const
 
1029
{
 
1030
    return d_func()->errorString;
 
1031
}
 
1032
 
 
1033
/*!
 
1034
    \fn qint64 QIODevice::readData(char *data, qint64 maxSize)
 
1035
 
 
1036
    Reads up to \a maxSize bytes from the device into \a data, and
 
1037
    returns the number of bytes read or -1 if an error occurred.
 
1038
 
 
1039
    This function is called by QIODevice. Reimplement this function
 
1040
    when creating a subclass of QIODevice.
 
1041
 
 
1042
    \sa read() readLine() writeData()
 
1043
*/
 
1044
 
 
1045
/*!
 
1046
    \fn qint64 QIODevice::writeData(const char *data, qint64 maxSize)
 
1047
 
 
1048
    Writes up to \a maxSize bytes from \a data to the device. Returns
 
1049
    the number of bytes written, or -1 if an error occurred.
 
1050
 
 
1051
    This function is called by QIODevice. Reimplement this function
 
1052
    when creating a subclass of QIODevice.
 
1053
 
 
1054
    \sa read() write()
 
1055
*/
 
1056
 
 
1057
/*!
 
1058
    \fn QIODevice::Offset QIODevice::status() const
 
1059
 
 
1060
    For device specific error handling, please refer to the
 
1061
    individual device documentation.
 
1062
 
 
1063
    \sa qobject_cast()
 
1064
*/
 
1065
 
 
1066
/*!
 
1067
    \fn QIODevice::Offset QIODevice::at() const
 
1068
 
 
1069
    Use pos() instead.
 
1070
*/
 
1071
 
 
1072
/*!
 
1073
    \fn bool QIODevice::at(Offset offset)
 
1074
 
 
1075
    Use seek(\a offset) instead.
 
1076
*/
 
1077
 
 
1078
/*! \fn int QIODevice::flags() const
 
1079
 
 
1080
    Use openMode() instead.
 
1081
*/
 
1082
 
 
1083
/*! \fn int QIODevice::getch()
 
1084
 
 
1085
    Use getChar() instead.
 
1086
*/
 
1087
 
 
1088
/*!
 
1089
    \fn bool QIODevice::isAsynchronous() const
 
1090
 
 
1091
    This functionality is no longer available. This function always
 
1092
    returns true.
 
1093
*/
 
1094
 
 
1095
/*!
 
1096
    \fn bool QIODevice::isBuffered() const
 
1097
 
 
1098
    Use !(openMode() & QIODevice::Unbuffered) instead.
 
1099
*/
 
1100
 
 
1101
/*!
 
1102
    \fn bool QIODevice::isCombinedAccess() const
 
1103
 
 
1104
    Use openMode() instead.
 
1105
*/
 
1106
 
 
1107
/*!
 
1108
    \fn bool QIODevice::isDirectAccess() const
 
1109
 
 
1110
    Use !isSequential() instead.
 
1111
*/
 
1112
 
 
1113
/*!
 
1114
    \fn bool QIODevice::isInactive() const
 
1115
 
 
1116
    Use isOpen(), isReadable(), or isWritable() instead.
 
1117
*/
 
1118
 
 
1119
/*!
 
1120
    \fn bool QIODevice::isRaw() const
 
1121
 
 
1122
    Use openMode() instead.
 
1123
*/
 
1124
 
 
1125
/*!
 
1126
    \fn bool QIODevice::isSequentialAccess() const
 
1127
 
 
1128
    Use isSequential() instead.
 
1129
*/
 
1130
 
 
1131
/*!
 
1132
    \fn bool QIODevice::isSynchronous() const
 
1133
 
 
1134
    This functionality is no longer available. This function always
 
1135
    returns false.
 
1136
*/
 
1137
 
 
1138
/*!
 
1139
    \fn bool QIODevice::isTranslated() const
 
1140
 
 
1141
    Use openMode() instead.
 
1142
*/
 
1143
 
 
1144
/*!
 
1145
    \fn bool QIODevice::mode() const
 
1146
 
 
1147
    Use openMode() instead.
 
1148
*/
 
1149
 
 
1150
/*! \fn int QIODevice::putch(int ch)
 
1151
 
 
1152
    Use putChar(\a ch) instead.
 
1153
*/
 
1154
 
 
1155
/*! \fn int QIODevice::ungetch(int ch)
 
1156
 
 
1157
    Use ungetChar(\a ch) instead.
 
1158
*/
 
1159
 
 
1160
/*!
 
1161
    \fn quint64 QIODevice::readBlock(char *data, quint64 size)
 
1162
 
 
1163
    Use read(\a data, \a size) instead.
 
1164
*/
 
1165
 
 
1166
/*! \fn int QIODevice::state() const
 
1167
 
 
1168
    Use isOpen() instead.
 
1169
*/
 
1170
 
 
1171
/*!
 
1172
    \fn qint64 QIODevice::writeBlock(const char *data, quint64 size)
 
1173
 
 
1174
    Use write(\a data, \a size) instead.
 
1175
*/
 
1176
 
 
1177
/*!
 
1178
    \fn qint64 QIODevice::writeBlock(const QByteArray &data)
 
1179
 
 
1180
    Use write(\a data) instead.
 
1181
*/
 
1182
 
 
1183
#if defined QT3_SUPPORT
 
1184
QIODevice::Status QIODevice::status() const
 
1185
{
 
1186
#if !defined(QT_NO_QOBJECT)
 
1187
    const QFile *f = qobject_cast<const QFile *>(this);
 
1188
    if (f) return (int) f->error();
 
1189
#endif
 
1190
    return isOpen() ? 0 /* IO_Ok */ : 8 /* IO_UnspecifiedError */;
 
1191
}
 
1192
 
 
1193
/*!
 
1194
    For device specific error handling, please refer to the
 
1195
    individual device documentation.
 
1196
 
 
1197
    \sa qobject_cast()
 
1198
*/
 
1199
void QIODevice::resetStatus()
 
1200
{
 
1201
#if !defined(QT_NO_QOBJECT)
 
1202
    QFile *f = qobject_cast<QFile *>(this);
 
1203
    if (f) f->unsetError();
 
1204
#endif
 
1205
}
 
1206
#endif