/qt-everywhere-opensource-src-4.8.2/src/corelib/io/qiodevice.cpp

# · C++ · 1855 lines · 805 code · 167 blank · 883 comment · 209 complexity · 746f3ac003c4f00fd5074956ab85f035 MD5 · raw file

Large files are truncated click here to view the full file

  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
  4. ** All rights reserved.
  5. ** Contact: Nokia Corporation (qt-info@nokia.com)
  6. **
  7. ** This file is part of the QtCore module of the Qt Toolkit.
  8. **
  9. ** $QT_BEGIN_LICENSE:LGPL$
  10. ** GNU Lesser General Public License Usage
  11. ** This file may be used under the terms of the GNU Lesser General Public
  12. ** License version 2.1 as published by the Free Software Foundation and
  13. ** appearing in the file LICENSE.LGPL included in the packaging of this
  14. ** file. Please review the following information to ensure the GNU Lesser
  15. ** General Public License version 2.1 requirements will be met:
  16. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  17. **
  18. ** In addition, as a special exception, Nokia gives you certain additional
  19. ** rights. These rights are described in the Nokia Qt LGPL Exception
  20. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  21. **
  22. ** GNU General Public License Usage
  23. ** Alternatively, this file may be used under the terms of the GNU General
  24. ** Public License version 3.0 as published by the Free Software Foundation
  25. ** and appearing in the file LICENSE.GPL included in the packaging of this
  26. ** file. Please review the following information to ensure the GNU General
  27. ** Public License version 3.0 requirements will be met:
  28. ** http://www.gnu.org/copyleft/gpl.html.
  29. **
  30. ** Other Usage
  31. ** Alternatively, this file may be used in accordance with the terms and
  32. ** conditions contained in a signed written agreement between you and Nokia.
  33. **
  34. **
  35. **
  36. **
  37. **
  38. ** $QT_END_LICENSE$
  39. **
  40. ****************************************************************************/
  41. //#define QIODEVICE_DEBUG
  42. #include "qbytearray.h"
  43. #include "qdebug.h"
  44. #include "qiodevice_p.h"
  45. #include "qfile.h"
  46. #include "qstringlist.h"
  47. #include <limits.h>
  48. #ifdef QIODEVICE_DEBUG
  49. # include <ctype.h>
  50. #endif
  51. QT_BEGIN_NAMESPACE
  52. #ifdef QIODEVICE_DEBUG
  53. void debugBinaryString(const QByteArray &input)
  54. {
  55. QByteArray tmp;
  56. int startOffset = 0;
  57. for (int i = 0; i < input.size(); ++i) {
  58. tmp += input[i];
  59. if ((i % 16) == 15 || i == (input.size() - 1)) {
  60. printf("\n%15d:", startOffset);
  61. startOffset += tmp.size();
  62. for (int j = 0; j < tmp.size(); ++j)
  63. printf(" %02x", int(uchar(tmp[j])));
  64. for (int j = tmp.size(); j < 16 + 1; ++j)
  65. printf(" ");
  66. for (int j = 0; j < tmp.size(); ++j)
  67. printf("%c", isprint(int(uchar(tmp[j]))) ? tmp[j] : '.');
  68. tmp.clear();
  69. }
  70. }
  71. printf("\n\n");
  72. }
  73. void debugBinaryString(const char *data, qint64 maxlen)
  74. {
  75. debugBinaryString(QByteArray(data, maxlen));
  76. }
  77. #endif
  78. #define Q_VOID
  79. #define CHECK_MAXLEN(function, returnType) \
  80. do { \
  81. if (maxSize < 0) { \
  82. qWarning("QIODevice::"#function": Called with maxSize < 0"); \
  83. return returnType; \
  84. } \
  85. } while (0)
  86. #define CHECK_WRITABLE(function, returnType) \
  87. do { \
  88. if ((d->openMode & WriteOnly) == 0) { \
  89. if (d->openMode == NotOpen) \
  90. return returnType; \
  91. qWarning("QIODevice::"#function": ReadOnly device"); \
  92. return returnType; \
  93. } \
  94. } while (0)
  95. #define CHECK_READABLE(function, returnType) \
  96. do { \
  97. if ((d->openMode & ReadOnly) == 0) { \
  98. if (d->openMode == NotOpen) \
  99. return returnType; \
  100. qWarning("QIODevice::"#function": WriteOnly device"); \
  101. return returnType; \
  102. } \
  103. } while (0)
  104. /*! \internal
  105. */
  106. QIODevicePrivate::QIODevicePrivate()
  107. : openMode(QIODevice::NotOpen), buffer(QIODEVICE_BUFFERSIZE),
  108. pos(0), devicePos(0), seqDumpPos(0)
  109. , pPos(&pos), pDevicePos(&devicePos)
  110. , baseReadLineDataCalled(false)
  111. , firstRead(true)
  112. , accessMode(Unset)
  113. #ifdef QT_NO_QOBJECT
  114. , q_ptr(0)
  115. #endif
  116. {
  117. }
  118. /*! \internal
  119. */
  120. QIODevicePrivate::~QIODevicePrivate()
  121. {
  122. }
  123. /*!
  124. \class QIODevice
  125. \reentrant
  126. \brief The QIODevice class is the base interface class of all I/O
  127. devices in Qt.
  128. \ingroup io
  129. QIODevice provides both a common implementation and an abstract
  130. interface for devices that support reading and writing of blocks
  131. of data, such as QFile, QBuffer and QTcpSocket. QIODevice is
  132. abstract and can not be instantiated, but it is common to use the
  133. interface it defines to provide device-independent I/O features.
  134. For example, Qt's XML classes operate on a QIODevice pointer,
  135. allowing them to be used with various devices (such as files and
  136. buffers).
  137. Before accessing the device, open() must be called to set the
  138. correct OpenMode (such as ReadOnly or ReadWrite). You can then
  139. write to the device with write() or putChar(), and read by calling
  140. either read(), readLine(), or readAll(). Call close() when you are
  141. done with the device.
  142. QIODevice distinguishes between two types of devices:
  143. random-access devices and sequential devices.
  144. \list
  145. \o Random-access devices support seeking to arbitrary
  146. positions using seek(). The current position in the file is
  147. available by calling pos(). QFile and QBuffer are examples of
  148. random-access devices.
  149. \o Sequential devices don't support seeking to arbitrary
  150. positions. The data must be read in one pass. The functions
  151. pos() and size() don't work for sequential devices.
  152. QTcpSocket and QProcess are examples of sequential devices.
  153. \endlist
  154. You can use isSequential() to determine the type of device.
  155. QIODevice emits readyRead() when new data is available for
  156. reading; for example, if new data has arrived on the network or if
  157. additional data is appended to a file that you are reading
  158. from. You can call bytesAvailable() to determine the number of
  159. bytes that are currently available for reading. It's common to use
  160. bytesAvailable() together with the readyRead() signal when
  161. programming with asynchronous devices such as QTcpSocket, where
  162. fragments of data can arrive at arbitrary points in
  163. time. QIODevice emits the bytesWritten() signal every time a
  164. payload of data has been written to the device. Use bytesToWrite()
  165. to determine the current amount of data waiting to be written.
  166. Certain subclasses of QIODevice, such as QTcpSocket and QProcess,
  167. are asynchronous. This means that I/O functions such as write()
  168. or read() always return immediately, while communication with the
  169. device itself may happen when control goes back to the event loop.
  170. QIODevice provides functions that allow you to force these
  171. operations to be performed immediately, while blocking the
  172. calling thread and without entering the event loop. This allows
  173. QIODevice subclasses to be used without an event loop, or in
  174. a separate thread:
  175. \list
  176. \o waitForReadyRead() - This function suspends operation in the
  177. calling thread until new data is available for reading.
  178. \o waitForBytesWritten() - This function suspends operation in the
  179. calling thread until one payload of data has been written to the
  180. device.
  181. \o waitFor....() - Subclasses of QIODevice implement blocking
  182. functions for device-specific operations. For example, QProcess
  183. has a function called waitForStarted() which suspends operation in
  184. the calling thread until the process has started.
  185. \endlist
  186. Calling these functions from the main, GUI thread, may cause your
  187. user interface to freeze. Example:
  188. \snippet doc/src/snippets/code/src_corelib_io_qiodevice.cpp 0
  189. By subclassing QIODevice, you can provide the same interface to
  190. your own I/O devices. Subclasses of QIODevice are only required to
  191. implement the protected readData() and writeData() functions.
  192. QIODevice uses these functions to implement all its convenience
  193. functions, such as getChar(), readLine() and write(). QIODevice
  194. also handles access control for you, so you can safely assume that
  195. the device is opened in write mode if writeData() is called.
  196. Some subclasses, such as QFile and QTcpSocket, are implemented
  197. using a memory buffer for intermediate storing of data. This
  198. reduces the number of required device accessing calls, which are
  199. often very slow. Buffering makes functions like getChar() and
  200. putChar() fast, as they can operate on the memory buffer instead
  201. of directly on the device itself. Certain I/O operations, however,
  202. don't work well with a buffer. For example, if several users open
  203. the same device and read it character by character, they may end
  204. up reading the same data when they meant to read a separate chunk
  205. each. For this reason, QIODevice allows you to bypass any
  206. buffering by passing the Unbuffered flag to open(). When
  207. subclassing QIODevice, remember to bypass any buffer you may use
  208. when the device is open in Unbuffered mode.
  209. \sa QBuffer QFile QTcpSocket
  210. */
  211. /*!
  212. \typedef QIODevice::Offset
  213. \compat
  214. Use \c qint64 instead.
  215. */
  216. /*!
  217. \typedef QIODevice::Status
  218. \compat
  219. Use QIODevice::OpenMode instead, or see the documentation for
  220. specific devices.
  221. */
  222. /*!
  223. \enum QIODevice::OpenModeFlag
  224. This enum is used with open() to describe the mode in which a device
  225. is opened. It is also returned by openMode().
  226. \value NotOpen The device is not open.
  227. \value ReadOnly The device is open for reading.
  228. \value WriteOnly The device is open for writing.
  229. \value ReadWrite The device is open for reading and writing.
  230. \value Append The device is opened in append mode, so that all data is
  231. written to the end of the file.
  232. \value Truncate If possible, the device is truncated before it is opened.
  233. All earlier contents of the device are lost.
  234. \value Text When reading, the end-of-line terminators are
  235. translated to '\n'. When writing, the end-of-line
  236. terminators are translated to the local encoding, for
  237. example '\r\n' for Win32.
  238. \value Unbuffered Any buffer in the device is bypassed.
  239. Certain flags, such as \c Unbuffered and \c Truncate, are
  240. meaningless when used with some subclasses. Some of these
  241. restrictions are implied by the type of device that is represented
  242. by a subclass. In other cases, the restriction may be due to the
  243. implementation, or may be imposed by the underlying platform; for
  244. example, QTcpSocket does not support \c Unbuffered mode, and
  245. limitations in the native API prevent QFile from supporting \c
  246. Unbuffered on Windows.
  247. */
  248. /*! \fn QIODevice::bytesWritten(qint64 bytes)
  249. This signal is emitted every time a payload of data has been
  250. written to the device. The \a bytes argument is set to the number
  251. of bytes that were written in this payload.
  252. bytesWritten() is not emitted recursively; if you reenter the event loop
  253. or call waitForBytesWritten() inside a slot connected to the
  254. bytesWritten() signal, the signal will not be reemitted (although
  255. waitForBytesWritten() may still return true).
  256. \sa readyRead()
  257. */
  258. /*!
  259. \fn QIODevice::readyRead()
  260. This signal is emitted once every time new data is available for
  261. reading from the device. It will only be emitted again once new
  262. data is available, such as when a new payload of network data has
  263. arrived on your network socket, or when a new block of data has
  264. been appended to your device.
  265. readyRead() is not emitted recursively; if you reenter the event loop or
  266. call waitForReadyRead() inside a slot connected to the readyRead() signal,
  267. the signal will not be reemitted (although waitForReadyRead() may still
  268. return true).
  269. Note for developers implementing classes derived from QIODevice:
  270. you should always emit readyRead() when new data has arrived (do not
  271. emit it only because there's data still to be read in your
  272. buffers). Do not emit readyRead() in other conditions.
  273. \sa bytesWritten()
  274. */
  275. /*! \fn QIODevice::aboutToClose()
  276. This signal is emitted when the device is about to close. Connect
  277. this signal if you have operations that need to be performed
  278. before the device closes (e.g., if you have data in a separate
  279. buffer that needs to be written to the device).
  280. */
  281. /*!
  282. \fn QIODevice::readChannelFinished()
  283. \since 4.4
  284. This signal is emitted when the input (reading) stream is closed
  285. in this device. It is emitted as soon as the closing is detected,
  286. which means that there might still be data available for reading
  287. with read().
  288. \sa atEnd(), read()
  289. */
  290. #ifdef QT_NO_QOBJECT
  291. QIODevice::QIODevice()
  292. : d_ptr(new QIODevicePrivate)
  293. {
  294. d_ptr->q_ptr = this;
  295. }
  296. /*! \internal
  297. */
  298. QIODevice::QIODevice(QIODevicePrivate &dd)
  299. : d_ptr(&dd)
  300. {
  301. d_ptr->q_ptr = this;
  302. }
  303. #else
  304. /*!
  305. Constructs a QIODevice object.
  306. */
  307. QIODevice::QIODevice()
  308. : QObject(*new QIODevicePrivate, 0)
  309. {
  310. #if defined QIODEVICE_DEBUG
  311. QFile *file = qobject_cast<QFile *>(this);
  312. printf("%p QIODevice::QIODevice(\"%s\") %s\n", this, metaObject()->className(),
  313. qPrintable(file ? file->fileName() : QString()));
  314. #endif
  315. }
  316. /*!
  317. Constructs a QIODevice object with the given \a parent.
  318. */
  319. QIODevice::QIODevice(QObject *parent)
  320. : QObject(*new QIODevicePrivate, parent)
  321. {
  322. #if defined QIODEVICE_DEBUG
  323. printf("%p QIODevice::QIODevice(%p \"%s\")\n", this, parent, metaObject()->className());
  324. #endif
  325. }
  326. /*! \internal
  327. */
  328. QIODevice::QIODevice(QIODevicePrivate &dd, QObject *parent)
  329. : QObject(dd, parent)
  330. {
  331. }
  332. #endif
  333. /*!
  334. The destructor is virtual, and QIODevice is an abstract base
  335. class. This destructor does not call close(), but the subclass
  336. destructor might. If you are in doubt, call close() before
  337. destroying the QIODevice.
  338. */
  339. QIODevice::~QIODevice()
  340. {
  341. #if defined QIODEVICE_DEBUG
  342. printf("%p QIODevice::~QIODevice()\n", this);
  343. #endif
  344. }
  345. /*!
  346. Returns true if this device is sequential; otherwise returns
  347. false.
  348. Sequential devices, as opposed to a random-access devices, have no
  349. concept of a start, an end, a size, or a current position, and they
  350. do not support seeking. You can only read from the device when it
  351. reports that data is available. The most common example of a
  352. sequential device is a network socket. On Unix, special files such
  353. as /dev/zero and fifo pipes are sequential.
  354. Regular files, on the other hand, do support random access. They
  355. have both a size and a current position, and they also support
  356. seeking backwards and forwards in the data stream. Regular files
  357. are non-sequential.
  358. The QIODevice implementation returns false.
  359. \sa bytesAvailable()
  360. */
  361. bool QIODevice::isSequential() const
  362. {
  363. return false;
  364. }
  365. /*!
  366. Returns the mode in which the device has been opened;
  367. i.e. ReadOnly or WriteOnly.
  368. \sa OpenMode
  369. */
  370. QIODevice::OpenMode QIODevice::openMode() const
  371. {
  372. return d_func()->openMode;
  373. }
  374. /*!
  375. Sets the OpenMode of the device to \a openMode. Call this
  376. function to set the open mode if the flags change after the device
  377. has been opened.
  378. \sa openMode() OpenMode
  379. */
  380. void QIODevice::setOpenMode(OpenMode openMode)
  381. {
  382. Q_D(QIODevice);
  383. #if defined QIODEVICE_DEBUG
  384. printf("%p QIODevice::setOpenMode(0x%x)\n", this, int(openMode));
  385. #endif
  386. d->openMode = openMode;
  387. d->accessMode = QIODevicePrivate::Unset;
  388. d->firstRead = true;
  389. if (!isReadable())
  390. d->buffer.clear();
  391. }
  392. /*!
  393. If \a enabled is true, this function sets the \l Text flag on the device;
  394. otherwise the \l Text flag is removed. This feature is useful for classes
  395. that provide custom end-of-line handling on a QIODevice.
  396. The IO device should be opened before calling this function.
  397. \sa open(), setOpenMode()
  398. */
  399. void QIODevice::setTextModeEnabled(bool enabled)
  400. {
  401. Q_D(QIODevice);
  402. if (!isOpen()) {
  403. qWarning("QIODevice::setTextModeEnabled: The device is not open");
  404. return;
  405. }
  406. if (enabled)
  407. d->openMode |= Text;
  408. else
  409. d->openMode &= ~Text;
  410. }
  411. /*!
  412. Returns true if the \l Text flag is enabled; otherwise returns false.
  413. \sa setTextModeEnabled()
  414. */
  415. bool QIODevice::isTextModeEnabled() const
  416. {
  417. return d_func()->openMode & Text;
  418. }
  419. /*!
  420. Returns true if the device is open; otherwise returns false. A
  421. device is open if it can be read from and/or written to. By
  422. default, this function returns false if openMode() returns
  423. \c NotOpen.
  424. \sa openMode() OpenMode
  425. */
  426. bool QIODevice::isOpen() const
  427. {
  428. return d_func()->openMode != NotOpen;
  429. }
  430. /*!
  431. Returns true if data can be read from the device; otherwise returns
  432. false. Use bytesAvailable() to determine how many bytes can be read.
  433. This is a convenience function which checks if the OpenMode of the
  434. device contains the ReadOnly flag.
  435. \sa openMode() OpenMode
  436. */
  437. bool QIODevice::isReadable() const
  438. {
  439. return (openMode() & ReadOnly) != 0;
  440. }
  441. /*!
  442. Returns true if data can be written to the device; otherwise returns
  443. false.
  444. This is a convenience function which checks if the OpenMode of the
  445. device contains the WriteOnly flag.
  446. \sa openMode() OpenMode
  447. */
  448. bool QIODevice::isWritable() const
  449. {
  450. return (openMode() & WriteOnly) != 0;
  451. }
  452. /*!
  453. Opens the device and sets its OpenMode to \a mode. Returns true if successful;
  454. otherwise returns false. This function should be called from any
  455. reimplementations of open() or other functions that open the device.
  456. \sa openMode() OpenMode
  457. */
  458. bool QIODevice::open(OpenMode mode)
  459. {
  460. Q_D(QIODevice);
  461. d->openMode = mode;
  462. d->pos = (mode & Append) ? size() : qint64(0);
  463. d->buffer.clear();
  464. d->accessMode = QIODevicePrivate::Unset;
  465. d->firstRead = true;
  466. #if defined QIODEVICE_DEBUG
  467. printf("%p QIODevice::open(0x%x)\n", this, quint32(mode));
  468. #endif
  469. return true;
  470. }
  471. /*!
  472. First emits aboutToClose(), then closes the device and sets its
  473. OpenMode to NotOpen. The error string is also reset.
  474. \sa setOpenMode() OpenMode
  475. */
  476. void QIODevice::close()
  477. {
  478. Q_D(QIODevice);
  479. if (d->openMode == NotOpen)
  480. return;
  481. #if defined QIODEVICE_DEBUG
  482. printf("%p QIODevice::close()\n", this);
  483. #endif
  484. #ifndef QT_NO_QOBJECT
  485. emit aboutToClose();
  486. #endif
  487. d->openMode = NotOpen;
  488. d->errorString.clear();
  489. d->pos = 0;
  490. d->seqDumpPos = 0;
  491. d->buffer.clear();
  492. d->firstRead = true;
  493. }
  494. /*!
  495. For random-access devices, this function returns the position that
  496. data is written to or read from. For sequential devices or closed
  497. devices, where there is no concept of a "current position", 0 is
  498. returned.
  499. The current read/write position of the device is maintained internally by
  500. QIODevice, so reimplementing this function is not necessary. When
  501. subclassing QIODevice, use QIODevice::seek() to notify QIODevice about
  502. changes in the device position.
  503. \sa isSequential(), seek()
  504. */
  505. qint64 QIODevice::pos() const
  506. {
  507. Q_D(const QIODevice);
  508. #if defined QIODEVICE_DEBUG
  509. printf("%p QIODevice::pos() == %d\n", this, int(d->pos));
  510. #endif
  511. return d->pos;
  512. }
  513. /*!
  514. For open random-access devices, this function returns the size of the
  515. device. For open sequential devices, bytesAvailable() is returned.
  516. If the device is closed, the size returned will not reflect the actual
  517. size of the device.
  518. \sa isSequential(), pos()
  519. */
  520. qint64 QIODevice::size() const
  521. {
  522. return d_func()->isSequential() ? bytesAvailable() : qint64(0);
  523. }
  524. /*!
  525. For random-access devices, this function sets the current position
  526. to \a pos, returning true on success, or false if an error occurred.
  527. For sequential devices, the default behavior is to do nothing and
  528. return false.
  529. When subclassing QIODevice, you must call QIODevice::seek() at the
  530. start of your function to ensure integrity with QIODevice's
  531. built-in buffer. The base implementation always returns true.
  532. \sa pos(), isSequential()
  533. */
  534. bool QIODevice::seek(qint64 pos)
  535. {
  536. Q_D(QIODevice);
  537. if (d->openMode == NotOpen) {
  538. qWarning("QIODevice::seek: The device is not open");
  539. return false;
  540. }
  541. if (pos < 0) {
  542. qWarning("QIODevice::seek: Invalid pos: %d", int(pos));
  543. return false;
  544. }
  545. #if defined QIODEVICE_DEBUG
  546. printf("%p QIODevice::seek(%d), before: d->pos = %d, d->buffer.size() = %d\n",
  547. this, int(pos), int(d->pos), d->buffer.size());
  548. #endif
  549. qint64 offset = pos - d->pos;
  550. if (!d->isSequential()) {
  551. d->pos = pos;
  552. d->devicePos = pos;
  553. }
  554. if (offset < 0
  555. || offset >= qint64(d->buffer.size()))
  556. // When seeking backwards, an operation that is only allowed for
  557. // random-access devices, the buffer is cleared. The next read
  558. // operation will then refill the buffer. We can optimize this, if we
  559. // find that seeking backwards becomes a significant performance hit.
  560. d->buffer.clear();
  561. else if (!d->buffer.isEmpty())
  562. d->buffer.skip(int(offset));
  563. #if defined QIODEVICE_DEBUG
  564. printf("%p \tafter: d->pos == %d, d->buffer.size() == %d\n", this, int(d->pos),
  565. d->buffer.size());
  566. #endif
  567. return true;
  568. }
  569. /*!
  570. Returns true if the current read and write position is at the end
  571. of the device (i.e. there is no more data available for reading on
  572. the device); otherwise returns false.
  573. For some devices, atEnd() can return true even though there is more data
  574. to read. This special case only applies to devices that generate data in
  575. direct response to you calling read() (e.g., \c /dev or \c /proc files on
  576. Unix and Mac OS X, or console input / \c stdin on all platforms).
  577. \sa bytesAvailable(), read(), isSequential()
  578. */
  579. bool QIODevice::atEnd() const
  580. {
  581. Q_D(const QIODevice);
  582. #if defined QIODEVICE_DEBUG
  583. printf("%p QIODevice::atEnd() returns %s, d->openMode == %d, d->pos == %d\n", this, (d->openMode == NotOpen || d->pos == size()) ? "true" : "false",
  584. int(d->openMode), int(d->pos));
  585. #endif
  586. return d->openMode == NotOpen || (d->buffer.isEmpty() && bytesAvailable() == 0);
  587. }
  588. /*!
  589. Seeks to the start of input for random-access devices. Returns
  590. true on success; otherwise returns false (for example, if the
  591. device is not open).
  592. Note that when using a QTextStream on a QFile, calling reset() on
  593. the QFile will not have the expected result because QTextStream
  594. buffers the file. Use the QTextStream::seek() function instead.
  595. \sa seek()
  596. */
  597. bool QIODevice::reset()
  598. {
  599. #if defined QIODEVICE_DEBUG
  600. printf("%p QIODevice::reset()\n", this);
  601. #endif
  602. return seek(0);
  603. }
  604. /*!
  605. Returns the number of bytes that are available for reading. This
  606. function is commonly used with sequential devices to determine the
  607. number of bytes to allocate in a buffer before reading.
  608. Subclasses that reimplement this function must call the base
  609. implementation in order to include the size of QIODevices' buffer. Example:
  610. \snippet doc/src/snippets/code/src_corelib_io_qiodevice.cpp 1
  611. \sa bytesToWrite(), readyRead(), isSequential()
  612. */
  613. qint64 QIODevice::bytesAvailable() const
  614. {
  615. Q_D(const QIODevice);
  616. if (!d->isSequential())
  617. return qMax(size() - d->pos, qint64(0));
  618. return d->buffer.size();
  619. }
  620. /*!
  621. For buffered devices, this function returns the number of bytes
  622. waiting to be written. For devices with no buffer, this function
  623. returns 0.
  624. \sa bytesAvailable(), bytesWritten(), isSequential()
  625. */
  626. qint64 QIODevice::bytesToWrite() const
  627. {
  628. return qint64(0);
  629. }
  630. #ifdef Q_CC_RVCT
  631. // arm mode makes the 64-bit integer operations much faster in RVCT 2.2
  632. #pragma push
  633. #pragma arm
  634. #endif
  635. /*!
  636. Reads at most \a maxSize bytes from the device into \a data, and
  637. returns the number of bytes read. If an error occurs, such as when
  638. attempting to read from a device opened in WriteOnly mode, this
  639. function returns -1.
  640. 0 is returned when no more data is available for reading. However,
  641. reading past the end of the stream is considered an error, so this
  642. function returns -1 in those cases (that is, reading on a closed
  643. socket or after a process has died).
  644. \sa readData() readLine() write()
  645. */
  646. qint64 QIODevice::read(char *data, qint64 maxSize)
  647. {
  648. Q_D(QIODevice);
  649. #if defined QIODEVICE_DEBUG
  650. printf("%p QIODevice::read(%p, %d), d->pos = %d, d->buffer.size() = %d\n",
  651. this, data, int(maxSize), int(d->pos), int(d->buffer.size()));
  652. #endif
  653. // Short circuit for getChar()
  654. if (maxSize == 1) {
  655. int chint;
  656. while ((chint = d->buffer.getChar()) != -1) {
  657. ++(*d->pPos);
  658. char c = char(uchar(chint));
  659. if (c == '\r' && (d->openMode & Text))
  660. continue;
  661. *data = c;
  662. #if defined QIODEVICE_DEBUG
  663. printf("%p \tread 0x%hhx (%c) returning 1 (shortcut)\n", this,
  664. int(c), isprint(c) ? c : '?');
  665. #endif
  666. return qint64(1);
  667. }
  668. }
  669. CHECK_MAXLEN(read, qint64(-1));
  670. qint64 readSoFar = 0;
  671. bool moreToRead = true;
  672. do {
  673. // Try reading from the buffer.
  674. int lastReadChunkSize = d->buffer.read(data, maxSize);
  675. if (lastReadChunkSize > 0) {
  676. *d->pPos += lastReadChunkSize;
  677. readSoFar += lastReadChunkSize;
  678. // fast exit when satisfied by buffer
  679. if (lastReadChunkSize == maxSize && !(d->openMode & Text))
  680. return readSoFar;
  681. data += lastReadChunkSize;
  682. maxSize -= lastReadChunkSize;
  683. #if defined QIODEVICE_DEBUG
  684. printf("%p \treading %d bytes from buffer into position %d\n", this, lastReadChunkSize,
  685. int(readSoFar) - lastReadChunkSize);
  686. #endif
  687. } else {
  688. if (d->firstRead) {
  689. // this is the first time the file has been read, check it's valid and set up pos pointers
  690. // for fast pos updates.
  691. CHECK_READABLE(read, qint64(-1));
  692. d->firstRead = false;
  693. if (d->isSequential()) {
  694. d->pPos = &d->seqDumpPos;
  695. d->pDevicePos = &d->seqDumpPos;
  696. }
  697. }
  698. if (!maxSize)
  699. return readSoFar;
  700. if ((d->openMode & Unbuffered) == 0 && maxSize < QIODEVICE_BUFFERSIZE) {
  701. // In buffered mode, we try to fill up the QIODevice buffer before
  702. // we do anything else.
  703. // buffer is empty at this point, try to fill it
  704. int bytesToBuffer = QIODEVICE_BUFFERSIZE;
  705. char *writePointer = d->buffer.reserve(bytesToBuffer);
  706. // Make sure the device is positioned correctly.
  707. if (d->pos != d->devicePos && !d->isSequential() && !seek(d->pos))
  708. return readSoFar ? readSoFar : qint64(-1);
  709. qint64 readFromDevice = readData(writePointer, bytesToBuffer);
  710. d->buffer.chop(bytesToBuffer - (readFromDevice < 0 ? 0 : int(readFromDevice)));
  711. if (readFromDevice > 0) {
  712. *d->pDevicePos += readFromDevice;
  713. #if defined QIODEVICE_DEBUG
  714. printf("%p \treading %d from device into buffer\n", this, int(readFromDevice));
  715. #endif
  716. if (!d->buffer.isEmpty()) {
  717. lastReadChunkSize = d->buffer.read(data, maxSize);
  718. readSoFar += lastReadChunkSize;
  719. data += lastReadChunkSize;
  720. maxSize -= lastReadChunkSize;
  721. *d->pPos += lastReadChunkSize;
  722. #if defined QIODEVICE_DEBUG
  723. printf("%p \treading %d bytes from buffer at position %d\n", this,
  724. lastReadChunkSize, int(readSoFar));
  725. #endif
  726. }
  727. }
  728. }
  729. }
  730. // If we need more, try reading from the device.
  731. if (maxSize > 0) {
  732. // Make sure the device is positioned correctly.
  733. if (d->pos != d->devicePos && !d->isSequential() && !seek(d->pos))
  734. return readSoFar ? readSoFar : qint64(-1);
  735. qint64 readFromDevice = readData(data, maxSize);
  736. #if defined QIODEVICE_DEBUG
  737. printf("%p \treading %d bytes from device (total %d)\n", this, int(readFromDevice), int(readSoFar));
  738. #endif
  739. if (readFromDevice == -1 && readSoFar == 0) {
  740. // error and we haven't read anything: return immediately
  741. return -1;
  742. }
  743. if (readFromDevice > 0) {
  744. lastReadChunkSize += int(readFromDevice);
  745. readSoFar += readFromDevice;
  746. data += readFromDevice;
  747. maxSize -= readFromDevice;
  748. *d->pPos += readFromDevice;
  749. *d->pDevicePos += readFromDevice;
  750. }
  751. }
  752. // Best attempt has been made to read data, don't try again except for text mode adjustment below
  753. moreToRead = false;
  754. if (readSoFar && d->openMode & Text) {
  755. char *readPtr = data - lastReadChunkSize;
  756. const char *endPtr = data;
  757. if (readPtr < endPtr) {
  758. // optimization to avoid initial self-assignment
  759. while (*readPtr != '\r') {
  760. if (++readPtr == endPtr)
  761. return readSoFar;
  762. }
  763. char *writePtr = readPtr;
  764. while (readPtr < endPtr) {
  765. char ch = *readPtr++;
  766. if (ch != '\r')
  767. *writePtr++ = ch;
  768. else {
  769. --readSoFar;
  770. --data;
  771. ++maxSize;
  772. }
  773. }
  774. // Make sure we get more data if there is room for more. This
  775. // is very important for when someone seeks to the start of a
  776. // '\r\n' and reads one character - they should get the '\n'.
  777. moreToRead = (readPtr != writePtr);
  778. }
  779. }
  780. } while (moreToRead);
  781. #if defined QIODEVICE_DEBUG
  782. printf("%p \treturning %d, d->pos == %d, d->buffer.size() == %d\n", this,
  783. int(readSoFar), int(d->pos), d->buffer.size());
  784. debugBinaryString(data - readSoFar, readSoFar);
  785. #endif
  786. return readSoFar;
  787. }
  788. #ifdef Q_CC_RVCT
  789. #pragma pop
  790. #endif
  791. /*!
  792. \overload
  793. Reads at most \a maxSize bytes from the device, and returns the
  794. data read as a QByteArray.
  795. This function has no way of reporting errors; returning an empty
  796. QByteArray() can mean either that no data was currently available
  797. for reading, or that an error occurred.
  798. */
  799. QByteArray QIODevice::read(qint64 maxSize)
  800. {
  801. Q_D(QIODevice);
  802. QByteArray result;
  803. CHECK_MAXLEN(read, result);
  804. #if defined QIODEVICE_DEBUG
  805. printf("%p QIODevice::read(%d), d->pos = %d, d->buffer.size() = %d\n",
  806. this, int(maxSize), int(d->pos), int(d->buffer.size()));
  807. #else
  808. Q_UNUSED(d);
  809. #endif
  810. if (maxSize != qint64(int(maxSize))) {
  811. qWarning("QIODevice::read: maxSize argument exceeds QByteArray size limit");
  812. maxSize = INT_MAX;
  813. }
  814. qint64 readBytes = 0;
  815. if (maxSize) {
  816. result.resize(int(maxSize));
  817. if (!result.size()) {
  818. // If resize fails, read incrementally.
  819. qint64 readResult;
  820. do {
  821. result.resize(int(qMin(maxSize, result.size() + QIODEVICE_BUFFERSIZE)));
  822. readResult = read(result.data() + readBytes, result.size() - readBytes);
  823. if (readResult > 0 || readBytes == 0)
  824. readBytes += readResult;
  825. } while (readResult == QIODEVICE_BUFFERSIZE);
  826. } else {
  827. readBytes = read(result.data(), result.size());
  828. }
  829. }
  830. if (readBytes <= 0)
  831. result.clear();
  832. else
  833. result.resize(int(readBytes));
  834. return result;
  835. }
  836. /*!
  837. \overload
  838. Reads all available data from the device, and returns it as a
  839. QByteArray.
  840. This function has no way of reporting errors; returning an empty
  841. QByteArray() can mean either that no data was currently available
  842. for reading, or that an error occurred.
  843. */
  844. QByteArray QIODevice::readAll()
  845. {
  846. Q_D(QIODevice);
  847. #if defined QIODEVICE_DEBUG
  848. printf("%p QIODevice::readAll(), d->pos = %d, d->buffer.size() = %d\n",
  849. this, int(d->pos), int(d->buffer.size()));
  850. #endif
  851. QByteArray result;
  852. qint64 readBytes = 0;
  853. // flush internal read buffer
  854. if (!(d->openMode & Text) && !d->buffer.isEmpty()) {
  855. result = d->buffer.readAll();
  856. readBytes = result.size();
  857. d->pos += readBytes;
  858. }
  859. qint64 theSize;
  860. if (d->isSequential() || (theSize = size()) == 0) {
  861. // Size is unknown, read incrementally.
  862. qint64 readResult;
  863. do {
  864. result.resize(result.size() + QIODEVICE_BUFFERSIZE);
  865. readResult = read(result.data() + readBytes, result.size() - readBytes);
  866. if (readResult > 0 || readBytes == 0)
  867. readBytes += readResult;
  868. } while (readResult > 0);
  869. } else {
  870. // Read it all in one go.
  871. // If resize fails, don't read anything.
  872. result.resize(int(readBytes + theSize - d->pos));
  873. readBytes += read(result.data() + readBytes, result.size() - readBytes);
  874. }
  875. if (readBytes <= 0)
  876. result.clear();
  877. else
  878. result.resize(int(readBytes));
  879. return result;
  880. }
  881. #ifdef Q_CC_RVCT
  882. // arm mode makes the 64-bit integer operations much faster in RVCT 2.2
  883. #pragma push
  884. #pragma arm
  885. #endif
  886. /*!
  887. This function reads a line of ASCII characters from the device, up
  888. to a maximum of \a maxSize - 1 bytes, stores the characters in \a
  889. data, and returns the number of bytes read. If a line could not be
  890. read but no error ocurred, this function returns 0. If an error
  891. occurs, this function returns the length of what could be read, or
  892. -1 if nothing was read.
  893. A terminating '\0' byte is always appended to \a data, so \a
  894. maxSize must be larger than 1.
  895. Data is read until either of the following conditions are met:
  896. \list
  897. \o The first '\n' character is read.
  898. \o \a maxSize - 1 bytes are read.
  899. \o The end of the device data is detected.
  900. \endlist
  901. For example, the following code reads a line of characters from a
  902. file:
  903. \snippet doc/src/snippets/code/src_corelib_io_qiodevice.cpp 2
  904. The newline character ('\n') is included in the buffer. If a
  905. newline is not encountered before maxSize - 1 bytes are read, a
  906. newline will not be inserted into the buffer. On windows newline
  907. characters are replaced with '\n'.
  908. This function calls readLineData(), which is implemented using
  909. repeated calls to getChar(). You can provide a more efficient
  910. implementation by reimplementing readLineData() in your own
  911. subclass.
  912. \sa getChar(), read(), write()
  913. */
  914. qint64 QIODevice::readLine(char *data, qint64 maxSize)
  915. {
  916. Q_D(QIODevice);
  917. if (maxSize < 2) {
  918. qWarning("QIODevice::readLine: Called with maxSize < 2");
  919. return qint64(-1);
  920. }
  921. #if defined QIODEVICE_DEBUG
  922. printf("%p QIODevice::readLine(%p, %d), d->pos = %d, d->buffer.size() = %d\n",
  923. this, data, int(maxSize), int(d->pos), int(d->buffer.size()));
  924. #endif
  925. // Leave room for a '\0'
  926. --maxSize;
  927. const bool sequential = d->isSequential();
  928. qint64 readSoFar = 0;
  929. if (!d->buffer.isEmpty()) {
  930. readSoFar = d->buffer.readLine(data, maxSize);
  931. if (!sequential)
  932. d->pos += readSoFar;
  933. #if defined QIODEVICE_DEBUG
  934. printf("%p \tread from buffer: %d bytes, last character read: %hhx\n", this,
  935. int(readSoFar), data[int(readSoFar) - 1]);
  936. if (readSoFar)
  937. debugBinaryString(data, int(readSoFar));
  938. #endif
  939. #if defined(Q_OS_SYMBIAN)
  940. // Open C fgets strips '\r' but readSoFar gets returned as if it was still there
  941. if ((d->openMode & Text) &&
  942. readSoFar > 1 &&
  943. data[readSoFar - 1] == '\0' &&
  944. data[readSoFar - 2] == '\n') {
  945. --readSoFar;
  946. }
  947. #endif
  948. if (readSoFar && data[readSoFar - 1] == '\n') {
  949. if (d->openMode & Text) {
  950. // QRingBuffer::readLine() isn't Text aware.
  951. if (readSoFar > 1 && data[readSoFar - 2] == '\r') {
  952. --readSoFar;
  953. data[readSoFar - 1] = '\n';
  954. }
  955. }
  956. data[readSoFar] = '\0';
  957. return readSoFar;
  958. }
  959. }
  960. if (d->pos != d->devicePos && !sequential && !seek(d->pos))
  961. return qint64(-1);
  962. d->baseReadLineDataCalled = false;
  963. qint64 readBytes = readLineData(data + readSoFar, maxSize - readSoFar);
  964. #if defined QIODEVICE_DEBUG
  965. printf("%p \tread from readLineData: %d bytes, readSoFar = %d bytes\n", this,
  966. int(readBytes), int(readSoFar));
  967. if (readBytes > 0) {
  968. debugBinaryString(data, int(readSoFar + readBytes));
  969. }
  970. #endif
  971. if (readBytes < 0) {
  972. data[readSoFar] = '\0';
  973. return readSoFar ? readSoFar : -1;
  974. }
  975. readSoFar += readBytes;
  976. if (!d->baseReadLineDataCalled && !sequential) {
  977. d->pos += readBytes;
  978. // If the base implementation was not called, then we must
  979. // assume the device position is invalid and force a seek.
  980. d->devicePos = qint64(-1);
  981. }
  982. data[readSoFar] = '\0';
  983. if (d->openMode & Text) {
  984. #if defined(Q_OS_SYMBIAN)
  985. // Open C fgets strips '\r' but readSoFar gets returned as if it was still there
  986. if (readSoFar > 1 && data[readSoFar - 1] == '\0' && data[readSoFar - 2] == '\n') {
  987. --readSoFar;
  988. }
  989. #endif
  990. if (readSoFar > 1 && data[readSoFar - 1] == '\n' && data[readSoFar - 2] == '\r') {
  991. data[readSoFar - 2] = '\n';
  992. data[readSoFar - 1] = '\0';
  993. --readSoFar;
  994. }
  995. }
  996. #if defined QIODEVICE_DEBUG
  997. printf("%p \treturning %d, d->pos = %d, d->buffer.size() = %d, size() = %d\n",
  998. this, int(readSoFar), int(d->pos), d->buffer.size(), int(size()));
  999. debugBinaryString(data, int(readSoFar));
  1000. #endif
  1001. return readSoFar;
  1002. }
  1003. /*!
  1004. \overload
  1005. Reads a line from the device, but no more than \a maxSize characters,
  1006. and returns the result as a QByteArray.
  1007. This function has no way of reporting errors; returning an empty
  1008. QByteArray() can mean either that no data was currently available
  1009. for reading, or that an error occurred.
  1010. */
  1011. QByteArray QIODevice::readLine(qint64 maxSize)
  1012. {
  1013. Q_D(QIODevice);
  1014. QByteArray result;
  1015. CHECK_MAXLEN(readLine, result);
  1016. #if defined QIODEVICE_DEBUG
  1017. printf("%p QIODevice::readLine(%d), d->pos = %d, d->buffer.size() = %d\n",
  1018. this, int(maxSize), int(d->pos), int(d->buffer.size()));
  1019. #else
  1020. Q_UNUSED(d);
  1021. #endif
  1022. if (maxSize > INT_MAX) {
  1023. qWarning("QIODevice::read: maxSize argument exceeds QByteArray size limit");
  1024. maxSize = INT_MAX;
  1025. }
  1026. result.resize(int(maxSize));
  1027. qint64 readBytes = 0;
  1028. if (!result.size()) {
  1029. // If resize fails or maxSize == 0, read incrementally
  1030. if (maxSize == 0)
  1031. maxSize = INT_MAX;
  1032. // The first iteration needs to leave an extra byte for the terminating null
  1033. result.resize(1);
  1034. qint64 readResult;
  1035. do {
  1036. result.resize(int(qMin(maxSize, result.size() + QIODEVICE_BUFFERSIZE)));
  1037. readResult = readLine(result.data() + readBytes, result.size() - readBytes);
  1038. if (readResult > 0 || readBytes == 0)
  1039. readBytes += readResult;
  1040. } while (readResult == QIODEVICE_BUFFERSIZE
  1041. && result[int(readBytes - 1)] != '\n');
  1042. } else
  1043. readBytes = readLine(result.data(), result.size());
  1044. if (readBytes <= 0)
  1045. result.clear();
  1046. else
  1047. result.resize(readBytes);
  1048. return result;
  1049. }
  1050. /*!
  1051. Reads up to \a maxSize characters into \a data and returns the
  1052. number of characters read.
  1053. This function is called by readLine(), and provides its base
  1054. implementation, using getChar(). Buffered devices can improve the
  1055. performance of readLine() by reimplementing this function.
  1056. readLine() appends a '\0' byte to \a data; readLineData() does not
  1057. need to do this.
  1058. If you reimplement this function, be careful to return the correct
  1059. value: it should return the number of bytes read in this line,
  1060. including the terminating newline, or 0 if there is no line to be
  1061. read at this point. If an error occurs, it should return -1 if and
  1062. only if no bytes were read. Reading past EOF is considered an error.
  1063. */
  1064. qint64 QIODevice::readLineData(char *data, qint64 maxSize)
  1065. {
  1066. Q_D(QIODevice);
  1067. qint64 readSoFar = 0;
  1068. char c;
  1069. int lastReadReturn = 0;
  1070. d->baseReadLineDataCalled = true;
  1071. while (readSoFar < maxSize && (lastReadReturn = read(&c, 1)) == 1) {
  1072. *data++ = c;
  1073. ++readSoFar;
  1074. if (c == '\n')
  1075. break;
  1076. }
  1077. #if defined QIODEVICE_DEBUG
  1078. printf("%p QIODevice::readLineData(%p, %d), d->pos = %d, d->buffer.size() = %d, returns %d\n",
  1079. this, data, int(maxSize), int(d->pos), int(d->buffer.size()), int(readSoFar));
  1080. #endif
  1081. if (lastReadReturn != 1 && readSoFar == 0)
  1082. return isSequential() ? lastReadReturn : -1;
  1083. return readSoFar;
  1084. }
  1085. #ifdef Q_CC_RVCT
  1086. #pragma pop
  1087. #endif
  1088. /*!
  1089. Returns true if a complete line of data can be read from the device;
  1090. otherwise returns false.
  1091. Note that unbuffered devices, which have no way of determining what
  1092. can be read, always return false.
  1093. This function is often called in conjunction with the readyRead()
  1094. signal.
  1095. Subclasses that reimplement this function must call the base
  1096. implementation in order to include the contents of the QIODevice's buffer. Example:
  1097. \snippet doc/src/snippets/code/src_corelib_io_qiodevice.cpp 3
  1098. \sa readyRead(), readLine()
  1099. */
  1100. bool QIODevice::canReadLine() const
  1101. {
  1102. return d_func()->buffer.canReadLine();
  1103. }
  1104. /*!
  1105. Writes at most \a maxSize bytes of data from \a data to the
  1106. device. Returns the number of bytes that were actually written, or
  1107. -1 if an error occurred.
  1108. \sa read() writeData()
  1109. */
  1110. qint64 QIODevice::write(const char *data, qint64 maxSize)
  1111. {
  1112. Q_D(QIODevice);
  1113. CHECK_WRITABLE(write, qint64(-1));
  1114. CHECK_MAXLEN(write, qint64(-1));
  1115. const bool sequential = d->isSequential();
  1116. // Make sure the device is positioned correctly.
  1117. if (d->pos != d->devicePos && !sequential && !seek(d->pos))
  1118. return qint64(-1);
  1119. #ifdef Q_OS_WIN
  1120. if (d->openMode & Text) {
  1121. const char *endOfData = data + maxSize;
  1122. const char *startOfBlock = data;
  1123. qint64 writtenSoFar = 0;
  1124. forever {
  1125. const char *endOfBlock = startOfBlock;
  1126. while (endOfBlock < endOfData && *endOfBlock != '\n')
  1127. ++endOfBlock;
  1128. qint64 blockSize = endOfBlock - startOfBlock;
  1129. if (blockSize > 0) {
  1130. qint64 ret = writeData(startOfBlock, blockSize);
  1131. if (ret <= 0) {
  1132. if (writtenSoFar && !sequential)
  1133. d->buffer.skip(writtenSoFar);
  1134. return writtenSoFar ? writtenSoFar : ret;
  1135. }
  1136. if (!sequential) {
  1137. d->pos += ret;
  1138. d->devicePos += ret;
  1139. }
  1140. writtenSoFar += ret;
  1141. }
  1142. if (endOfBlock == endOfData)
  1143. break;
  1144. qint64 ret = writeData("\r\n", 2);
  1145. if (ret <= 0) {
  1146. if (writtenSoFar && !sequential)
  1147. d->buffer.skip(writtenSoFar);
  1148. return writtenSoFar ? writtenSoFar : ret;
  1149. }
  1150. if (!sequential) {
  1151. d->pos += ret;
  1152. d->devicePos += ret;
  1153. }
  1154. ++writtenSoFar;
  1155. startOfBlock = endOfBlock + 1;
  1156. }
  1157. if (writtenSoFar && !sequential)
  1158. d->buffer.skip(writtenSoFar);
  1159. return writtenSoFar;
  1160. }
  1161. #endif
  1162. qint64 written = writeData(data, maxSize);
  1163. if (written > 0) {
  1164. if (!sequential) {
  1165. d->pos += written;
  1166. d->devicePos += written;
  1167. }
  1168. if (!d->buffer.isEmpty() && !sequential)
  1169. d->buffer.skip(written);
  1170. }
  1171. return written;
  1172. }
  1173. /*!
  1174. \since 4.5
  1175. \overload
  1176. Writes data from a zero-terminated string of 8-bit characters to the
  1177. device. Returns the number of bytes that were actually written, or
  1178. -1 if an error occurred. This is equivalent to
  1179. \code
  1180. ...
  1181. QIODevice::write(data, qstrlen(data));
  1182. ...
  1183. \endcode
  1184. \sa read() writeData()
  1185. */
  1186. qint64 QIODevice::write(const char *data)
  1187. {
  1188. return write(data, qstrlen(data));
  1189. }
  1190. /*! \fn qint64 QIODevice::write(const QByteArray &byteArray)
  1191. \overload
  1192. Writes the content of \a byteArray to the device. Returns the number of
  1193. bytes that were actually written, or -1 if an error occurred.
  1194. \sa read() writeData()
  1195. */
  1196. /*!
  1197. Puts the character \a c back into the device, and decrements the
  1198. current position unless the position is 0. This function is
  1199. usually called to "undo" a getChar() operation, such as when
  1200. writing a backtracking parser.
  1201. If \a c was not previously read from the device, the behavior is
  1202. undefined.
  1203. */
  1204. void QIODevice::ungetChar(char c)
  1205. {
  1206. Q_D(QIODevice);
  1207. CHECK_READABLE(read, Q_VOID);
  1208. #if defined QIODEVICE_DEBUG
  1209. printf("%p QIODevice::ungetChar(0x%hhx '%c')\n", this, c, isprint(c) ? c : '?');
  1210. #endif
  1211. d->buffer.ungetChar(c);
  1212. if (!d->isSequential())
  1213. --d->pos;
  1214. }
  1215. /*! \fn bool QIODevice::putChar(char c)
  1216. Writes the character \a c to the device. Returns true on success;
  1217. otherwise returns false.
  1218. \sa write() getChar() ungetChar()
  1219. */
  1220. bool QIODevice::putChar(char c)
  1221. {
  1222. return d_func()->putCharHelper(c);
  1223. }
  1224. /*!
  1225. \internal
  1226. */
  1227. bool QIODevicePrivate::putCharHelper(char c)
  1228. {
  1229. return q_func()->write(&c, 1) == 1;
  1230. }
  1231. /*!
  1232. \internal
  1233. */
  1234. qint64 QIODevicePrivate::peek(char *data, qint64 maxSize)
  1235. {
  1236. qint64 readBytes = q_func()->read(data, maxSize);
  1237. if (readBytes <= 0)
  1238. return readBytes;
  1239. buffer.ungetBlock(data, readBytes);
  1240. *pPos -= readBytes;
  1241. return readBytes;
  1242. }
  1243. /*!
  1244. \internal
  1245. */
  1246. QByteArray QIODevicePrivate::peek(qint64 maxSize)
  1247. {
  1248. QByteArray result = q_func()->read(maxSize);
  1249. if (result.isEmpty())
  1250. return result;
  1251. buffer.ungetBlock(result.constData(), result.size());
  1252. *pPos -= result.size();
  1253. return result;
  1254. }
  1255. /*! \fn bool QIODevice::getChar(char *c)
  1256. Reads one character from the device and stores it in \a c. If \a c
  1257. is 0, the character is discarded. Returns true on success;
  1258. otherwise returns false.
  1259. \sa read() putChar() ungetChar()
  1260. */
  1261. bool QIODevice::getChar(char *c)
  1262. {
  1263. // readability checked in read()
  1264. char ch;
  1265. return (1 == read(c ? c : &ch, 1));
  1266. }
  1267. /*!
  1268. \since 4.1
  1269. Reads at most \a maxSize bytes from the device into \a data, without side
  1270. effects (i.e., if you call read() after peek(), you will get the same
  1271. data). Returns the number of bytes read. If an error occurs, such as
  1272. when attempting to peek a device opened in WriteOnly mode, this function
  1273. returns -1.
  1274. 0 is returned when no more data is available for reading.
  1275. Example:
  1276. \snippet doc/src/snippets/code/src_corelib_io_qiodevice.cpp 4
  1277. \sa read()
  1278. */
  1279. qint64 QIODevice::peek(char *data, qint64 maxSize)
  1280. {
  1281. return d_func()->peek(data, maxSize);
  1282. }
  1283. /*!
  1284. \since 4.1
  1285. \overload
  1286. Peeks at most \a maxSize bytes from the device, returning the data peeked
  1287. as a QByteArray.
  1288. Example:
  1289. \snippet doc/src/snippets/code/src_corelib_io_qiodevice.cpp 5
  1290. This function has no way of reporting errors; returning an empty
  1291. QByteArray() can mean either that no data was currently available
  1292. for peeking, or that an error occurred.
  1293. \sa read()
  1294. */
  1295. QByteArray QIODevice::peek(qint64 maxSize)
  1296. {
  1297. return d_func()->peek(maxSize);
  1298. }
  1299. /*!
  1300. Blocks until new data is available for reading and the readyRead()
  1301. signal has been emitted, or until \a msecs milliseconds have
  1302. passed. If msecs is -1, this function will not time out.
  1303. Returns true if new data is available for reading; otherwise returns
  1304. false (if the operation timed out or if an error occurred).
  1305. This function can operate without an event loop. It is
  1306. useful when writing non-GUI applications and when performing
  1307. I/O operations in a non-GUI thread.
  1308. If called from within a slot connected to the readyRead() signal,
  1309. readyRead() will not be reemitted.
  1310. Reimplement this function to provide a blocking API for a custom
  1311. device. The default implementation does nothing, and returns false.
  1312. \warning Calling this function from the main (GUI) thread
  1313. might cause your user interface to freeze.
  1314. \sa waitForBytesWritten()
  1315. */
  1316. bool QIODevice::waitForReadyRead(int msecs)
  1317. {
  1318. Q_UNUSED(msecs);
  1319. return false;
  1320. }
  1321. /*!
  1322. For buffered devices, this function waits until a payload of
  1323. buffered written data has been written to the device and the
  1324. bytesWritten() signal has been emitted, or until \a msecs
  1325. milliseconds have passed. If msecs is -1, this function will
  1326. not time out. For unbuffered devices, it returns immediately.
  1327. Returns true if a payload of data was written to the device;
  1328. otherwise returns false (i.e. if the operation timed out, or if an
  1329. error occurred).
  1330. This function can operate without an event loop. It is
  1331. useful when writing non-GUI applications and when performing
  1332. I/O operations in a non-GUI thread.
  1333. If called from within a slot connected t…