Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qtextstream.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// Copyright (C) 2016 Intel Corporation.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:critical reason:data-parser
5
6//#define QTEXTSTREAM_DEBUG
7
8/*!
9 \class QTextStream
10 \inmodule QtCore
11
12 \brief The QTextStream class provides a convenient interface for
13 reading and writing text.
14
15 \ingroup io
16 \ingroup string-processing
17 \ingroup qtserialization
18 \reentrant
19
20 QTextStream can operate on a QIODevice, a QByteArray or a
21 QString. Using QTextStream's streaming operators, you can
22 conveniently read and write words, lines and numbers. For
23 generating text, QTextStream supports formatting options for field
24 padding and alignment, and formatting of numbers. Example:
25
26 \snippet code/src_corelib_io_qtextstream.cpp 0
27
28 It's also common to use QTextStream to read console input and write
29 console output. QTextStream is locale aware, and will automatically decode
30 standard input using the correct encoding. Example:
31
32 \snippet code/src_corelib_io_qtextstream.cpp 1
33
34 Besides using QTextStream's constructors, you can also set the
35 device or string QTextStream operates on by calling setDevice() or
36 setString(). You can seek to a position by calling seek(), and
37 atEnd() will return true when there is no data left to be read. If
38 you call flush(), QTextStream will empty all data from its write
39 buffer into the device and call flush() on the device.
40
41 Internally, QTextStream uses a Unicode based buffer, and
42 QStringConverter is used by QTextStream to automatically support
43 different encodings. By default, UTF-8
44 is used for reading and writing, but you can also set the encoding by
45 calling setEncoding(). Automatic Unicode detection is also
46 supported. When this feature is enabled (the default behavior),
47 QTextStream will detect the UTF-8, UTF-16 or the UTF-32 BOM (Byte Order Mark) and
48 switch to the appropriate UTF encoding when reading. QTextStream
49 does not write a BOM by default, but you can enable this by calling
50 setGenerateByteOrderMark(true). When QTextStream operates on a QString
51 directly, the encoding is disabled.
52
53 There are three general ways to use QTextStream when reading text
54 files:
55
56 \list
57
58 \li Chunk by chunk, by calling readLine() or readAll().
59
60 \li Word by word. QTextStream supports streaming into \l {QString}s,
61 \l {QByteArray}s and char* buffers. Words are delimited by space, and
62 leading white space is automatically skipped.
63
64 \li Character by character, by streaming into QChar or char types.
65 This method is often used for convenient input handling when
66 parsing files, independent of character encoding and end-of-line
67 semantics. To skip white space, call skipWhiteSpace().
68
69 \endlist
70
71 Since the text stream uses a buffer, you should not read from
72 the stream using the implementation of a superclass. For instance,
73 if you have a QFile and read from it directly using
74 QFile::readLine() instead of using the stream, the text stream's
75 internal position will be out of sync with the file's position.
76
77 By default, when reading numbers from a stream of text,
78 QTextStream will automatically detect the number's base
79 representation. For example, if the number starts with "0x", it is
80 assumed to be in hexadecimal form. If it starts with the digits
81 1-9, it is assumed to be in decimal form, and so on. You can set
82 the integer base, thereby disabling the automatic detection, by
83 calling setIntegerBase(). Example:
84
85 \snippet code/src_corelib_io_qtextstream.cpp 2
86
87 QTextStream supports many formatting options for generating text.
88 You can set the field width and pad character by calling
89 setFieldWidth() and setPadChar(). Use setFieldAlignment() to set
90 the alignment within each field. For real numbers, call
91 setRealNumberNotation() and setRealNumberPrecision() to set the
92 notation (SmartNotation, ScientificNotation, FixedNotation) and precision in
93 digits of the generated number. Some extra number formatting
94 options are also available through setNumberFlags().
95
96 \target QTextStream manipulators
97
98 Like \c <iostream> in the standard C++ library, QTextStream also
99 defines several global manipulator functions:
100
101 \table
102 \header \li Manipulator \li Description
103 \row \li Qt::bin \li Same as setIntegerBase(2).
104 \row \li Qt::oct \li Same as setIntegerBase(8).
105 \row \li Qt::dec \li Same as setIntegerBase(10).
106 \row \li Qt::hex \li Same as setIntegerBase(16).
107 \row \li Qt::showbase \li Same as setNumberFlags(numberFlags() | ShowBase).
108 \row \li Qt::forcesign \li Same as setNumberFlags(numberFlags() | ForceSign).
109 \row \li Qt::forcepoint \li Same as setNumberFlags(numberFlags() | ForcePoint).
110 \row \li Qt::noshowbase \li Same as setNumberFlags(numberFlags() & ~ShowBase).
111 \row \li Qt::noforcesign \li Same as setNumberFlags(numberFlags() & ~ForceSign).
112 \row \li Qt::noforcepoint \li Same as setNumberFlags(numberFlags() & ~ForcePoint).
113 \row \li Qt::uppercasebase \li Same as setNumberFlags(numberFlags() | UppercaseBase).
114 \row \li Qt::uppercasedigits \li Same as setNumberFlags(numberFlags() | UppercaseDigits).
115 \row \li Qt::lowercasebase \li Same as setNumberFlags(numberFlags() & ~UppercaseBase).
116 \row \li Qt::lowercasedigits \li Same as setNumberFlags(numberFlags() & ~UppercaseDigits).
117 \row \li Qt::fixed \li Same as setRealNumberNotation(FixedNotation).
118 \row \li Qt::scientific \li Same as setRealNumberNotation(ScientificNotation).
119 \row \li Qt::left \li Same as setFieldAlignment(AlignLeft).
120 \row \li Qt::right \li Same as setFieldAlignment(AlignRight).
121 \row \li Qt::center \li Same as setFieldAlignment(AlignCenter).
122 \row \li Qt::endl \li Same as operator<<('\\n') and flush().
123 \row \li Qt::flush \li Same as flush().
124 \row \li Qt::reset \li Same as reset().
125 \row \li Qt::ws \li Same as skipWhiteSpace().
126 \row \li Qt::bom \li Same as setGenerateByteOrderMark(true).
127 \endtable
128
129 In addition, Qt provides three global manipulators that take a
130 parameter: qSetFieldWidth(), qSetPadChar(), and
131 qSetRealNumberPrecision().
132
133 \sa QDataStream, QIODevice, QFile, QBuffer, QTcpSocket
134*/
135
136/*! \enum QTextStream::RealNumberNotation
137
138 This enum specifies which notations to use for expressing \c
139 float and \c double as strings.
140
141 \value ScientificNotation Scientific notation (\c{printf()}'s \c %e flag).
142 \value FixedNotation Fixed-point notation (\c{printf()}'s \c %f flag).
143 \value SmartNotation Scientific or fixed-point notation, depending on which makes most sense (\c{printf()}'s \c %g flag).
144
145 \sa setRealNumberNotation()
146*/
147
148/*! \enum QTextStream::FieldAlignment
149
150 This enum specifies how to align text in fields when the field is
151 wider than the text that occupies it.
152
153 \value AlignLeft Pad on the right side of fields.
154 \value AlignRight Pad on the left side of fields.
155 \value AlignCenter Pad on both sides of field.
156 \value AlignAccountingStyle Same as AlignRight, except that the
157 sign of a number is flush left.
158
159 \sa setFieldAlignment()
160*/
161
162/*! \enum QTextStream::NumberFlag
163
164 This enum specifies various flags that can be set to affect the
165 output of integers, \c{float}s, and \c{double}s.
166
167 \value ShowBase Show the base as a prefix if the base
168 is 16 ("0x"), 8 ("0"), or 2 ("0b").
169 \value ForcePoint Always put the decimal separator in numbers, even if
170 there are no decimals.
171 \value ForceSign Always put the sign in numbers, even for positive numbers.
172 \value UppercaseBase Use uppercase versions of base prefixes ("0X", "0B").
173 \value UppercaseDigits Use uppercase letters for expressing
174 digits 10 to 35 instead of lowercase.
175
176 \sa setNumberFlags()
177*/
178
179/*! \enum QTextStream::Status
180
181 This enum describes the current status of the text stream.
182
183 \value Ok The text stream is operating normally.
184 \value ReadPastEnd The text stream has read past the end of the
185 data in the underlying device.
186 \value ReadCorruptData The text stream has read corrupt data.
187 \value WriteFailed The text stream cannot write to the underlying device.
188
189 \sa status()
190*/
191
192#include "qtextstream.h"
193#include "private/qtextstream_p.h"
194#include "qbuffer.h"
195#include "qfile.h"
196#include "qnumeric.h"
197#include "qvarlengtharray.h"
198#include <private/qdebug_p.h>
199#include <private/qnumeric_p.h>
200#include <private/qtools_p.h>
201
202#include <locale.h>
203#include "private/qlocale_p.h"
204#include "private/qstringconverter_p.h"
205
206#include <stdlib.h>
207#include <limits.h>
208#include <new>
209
210// A precondition macro
211#define Q_VOID
212#define CHECK_VALID_STREAM(x) do {
213 if (!d->string && !d->device) {
214 qWarning("QTextStream: No device");
215 return x;
216 } } while (0)
217
218// Base implementations of operator>> for ints and reals
219#define IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(type) do {
220 Q_D(QTextStream);
221 CHECK_VALID_STREAM(*this);
222 qulonglong tmp;
223 switch (d->getNumber(&tmp)) {
224 case QTextStreamPrivate::npsOk:
225 i = (type)tmp;
226 break;
227 case QTextStreamPrivate::npsMissingDigit:
228 case QTextStreamPrivate::npsInvalidPrefix:
229 i = (type)0;
230 setStatus(atEnd() ? QTextStream::ReadPastEnd : QTextStream::ReadCorruptData);
231 break;
232 }
233 return *this; } while (0)
234
235#define IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(type) do {
236 Q_D(QTextStream);
237 CHECK_VALID_STREAM(*this);
238 double tmp;
239 if (d->getReal(&tmp)) {
240 f = (type)tmp;
241 } else {
242 f = (type)0;
243 setStatus(atEnd() ? QTextStream::ReadPastEnd : QTextStream::ReadCorruptData);
244 }
245 return *this; } while (0)
246
248
249using namespace Qt::StringLiterals;
250using namespace QtMiscUtils;
251
253
254//-------------------------------------------------------------------
255
256/*!
257 \internal
258*/
259QTextStreamPrivate::QTextStreamPrivate(QTextStream *q_ptr)
260 : readConverterSavedStateOffset(0),
261 locale(QLocale::c())
262{
263 this->q_ptr = q_ptr;
264 reset();
265}
266
267/*!
268 \internal
269*/
270QTextStreamPrivate::~QTextStreamPrivate()
271{
272 disconnectFromDevice();
273 if (deleteDevice) {
274#ifndef QT_NO_QOBJECT
275 device->blockSignals(true);
276#endif
277 delete device;
278 }
279}
280
281void QTextStreamPrivate::Params::reset()
282{
283 realNumberPrecision = 6;
284 integerBase = 0;
285 fieldWidth = 0;
286 padChar = u' ';
287 fieldAlignment = QTextStream::AlignRight;
288 realNumberNotation = QTextStream::SmartNotation;
289 numberFlags = { };
290}
291
292/*!
293 \internal
294*/
295void QTextStreamPrivate::reset()
296{
297 params.reset();
298
299 device = nullptr;
300 deleteDevice = false;
301 string = nullptr;
302 stringOffset = 0;
303 stringOpenMode = QTextStream::NotOpen;
304
305 readBufferOffset = 0;
306 readBufferStartDevicePos = 0;
307 lastTokenSize = 0;
308
309 hasWrittenData = false;
310 generateBOM = false;
311 encoding = QStringConverter::Utf8;
312 toUtf16 = QStringDecoder(encoding);
313 fromUtf16 = QStringEncoder(encoding);
314 autoDetectUnicode = true;
315}
316
317void QTextStreamPrivate::setupDevice(QIODevice *device)
318{
319 disconnectFromDevice();
320
321#ifndef QT_NO_QOBJECT
322 if (device) {
323 // Explicitly set a direct connection (though it would have been so
324 // anyway) so that QTextStream can be used from multiple threads when the
325 // application code is handling synchronization (see also QTBUG-12055).
326 aboutToCloseConnection = QObject::connect(
327 device, &QIODevice::aboutToClose, device, [this] { flushWriteBuffer(); },
328 Qt::DirectConnection);
329 }
330#else
331 Q_UNUSED(device);
332#endif
333}
334
335void QTextStreamPrivate::disconnectFromDevice()
336{
337#ifndef QT_NO_QOBJECT
338 QObject::disconnect(aboutToCloseConnection);
339 aboutToCloseConnection = {};
340#endif
341}
342
343/*!
344 \internal
345*/
346bool QTextStreamPrivate::fillReadBuffer(qint64 maxBytes)
347{
348 // no buffer next to the QString itself; this function should only
349 // be called internally, for devices.
350 Q_ASSERT(!string);
351 Q_ASSERT(device);
352
353 // handle text translation and bypass the Text flag in the device.
354 bool textModeEnabled = device->isTextModeEnabled();
355 if (textModeEnabled)
356 device->setTextModeEnabled(false);
357
358 // read raw data into a temporary buffer
359 char buf[QTEXTSTREAM_BUFFERSIZE];
360 qint64 bytesRead = 0;
361#if defined(Q_OS_WIN)
362 // On Windows, there is no non-blocking stdin - so we fall back to reading
363 // lines instead. If there is no QOBJECT, we read lines for all sequential
364 // devices; otherwise, we read lines only for stdin.
365 QFile *file = 0;
366 Q_UNUSED(file);
367 if (device->isSequential()
368#if !defined(QT_NO_QOBJECT)
369 && (file = qobject_cast<QFile *>(device)) && file->handle() == 0
370#endif
371 ) {
372 if (maxBytes != -1)
373 bytesRead = device->readLine(buf, qMin<qint64>(sizeof(buf), maxBytes));
374 else
375 bytesRead = device->readLine(buf, sizeof(buf));
376 } else
377#endif
378 {
379 if (maxBytes != -1)
380 bytesRead = device->read(buf, qMin<qint64>(sizeof(buf), maxBytes));
381 else
382 bytesRead = device->read(buf, sizeof(buf));
383 }
384
385 // reset the Text flag.
386 if (textModeEnabled)
387 device->setTextModeEnabled(true);
388
389 if (bytesRead <= 0)
390 return false;
391
392#ifndef QT_BOOTSTRAPPED
393 if (autoDetectUnicode) {
394 autoDetectUnicode = false;
395
396 auto e = QStringConverter::encodingForData(QByteArrayView(buf, bytesRead));
397 // QStringConverter::Locale implies unknown, so keep the current encoding
398 if (e) {
399 encoding = *e;
400 toUtf16 = QStringDecoder(encoding);
401 fromUtf16 = QStringEncoder(encoding);
402 }
403 }
404#if defined (QTEXTSTREAM_DEBUG)
405 qDebug("QTextStreamPrivate::fillReadBuffer(), using %s encoding", QStringConverter::nameForEncoding(encoding));
406#endif
407#endif
408
409#if defined (QTEXTSTREAM_DEBUG)
410 qDebug("QTextStreamPrivate::fillReadBuffer(), device->read(\"%s\", %d) == %d",
411 QtDebugUtils::toPrintable(buf, bytesRead, 32).constData(),
412 int(sizeof(buf)), int(bytesRead));
413#endif
414
415 qsizetype oldReadBufferSize = readBuffer.size();
416 readBuffer += toUtf16(QByteArrayView(buf, bytesRead));
417
418 // remove all '\r\n' in the string.
419 if (readBuffer.size() > oldReadBufferSize && textModeEnabled) {
420 QChar CR = u'\r';
421 QChar *writePtr = readBuffer.data() + oldReadBufferSize;
422 QChar *readPtr = readBuffer.data() + oldReadBufferSize;
423 QChar *endPtr = readBuffer.data() + readBuffer.size();
424
425 qsizetype n = oldReadBufferSize;
426 if (readPtr < endPtr) {
427 // Cut-off to avoid unnecessary self-copying.
428 while (*readPtr++ != CR) {
429 ++n;
430 if (++writePtr == endPtr)
431 break;
432 }
433 }
434 while (readPtr < endPtr) {
435 QChar ch = *readPtr++;
436 if (ch != CR) {
437 *writePtr++ = ch;
438 } else {
439 if (n < readBufferOffset)
440 --readBufferOffset;
441 --bytesRead;
442 }
443 ++n;
444 }
445 readBuffer.resize(writePtr - readBuffer.data());
446 }
447
448#if defined (QTEXTSTREAM_DEBUG)
449 qDebug("QTextStreamPrivate::fillReadBuffer() read %d bytes from device. readBuffer = [%s]",
450 int(bytesRead),
451 QtDebugUtils::toPrintable(readBuffer.toLatin1(), readBuffer.size(),
452 readBuffer.size()).constData());
453#endif
454 return true;
455}
456
457/*!
458 \internal
459*/
460void QTextStreamPrivate::resetReadBuffer()
461{
462 readBuffer.clear();
463 readBufferOffset = 0;
464 readBufferStartDevicePos = (device ? device->pos() : 0);
465}
466
467/*!
468 \internal
469*/
470void QTextStreamPrivate::flushWriteBuffer()
471{
472 // no buffer next to the QString itself; this function should only
473 // be called internally, for devices.
474 if (string || !device)
475 return;
476
477 // Stream went bye-bye already. Appending further data may succeed again,
478 // but would create a corrupted stream anyway.
479 if (status != QTextStream::Ok)
480 return;
481
482 if (writeBuffer.isEmpty())
483 return;
484
485#if defined (Q_OS_WIN)
486 // handle text translation and bypass the Text flag in the device.
487 bool textModeEnabled = device->isTextModeEnabled();
488 if (textModeEnabled) {
489 device->setTextModeEnabled(false);
490 writeBuffer.replace(u'\n', "\r\n"_L1);
491 }
492#endif
493
494 QByteArray data = fromUtf16(writeBuffer);
495 writeBuffer.clear();
496 hasWrittenData = true;
497
498 // write raw data to the device
499 qint64 bytesWritten = device->write(data);
500#if defined (QTEXTSTREAM_DEBUG)
501 qDebug("QTextStreamPrivate::flushWriteBuffer(), device->write(\"%s\") == %d",
502 QtDebugUtils::toPrintable(data.constData(), data.size(), 32).constData(),
503 int(bytesWritten));
504#endif
505
506#if defined (Q_OS_WIN)
507 // reset the text flag
508 if (textModeEnabled)
509 device->setTextModeEnabled(true);
510#endif
511
512 if (bytesWritten <= 0) {
513 status = QTextStream::WriteFailed;
514 return;
515 }
516
517 // flush the file
518#ifndef QT_NO_QOBJECT
519 QFileDevice *file = qobject_cast<QFileDevice *>(device);
520 bool flushed = !file || file->flush();
521#else
522 bool flushed = true;
523#endif
524
525#if defined (QTEXTSTREAM_DEBUG)
526 qDebug("QTextStreamPrivate::flushWriteBuffer() wrote %d bytes", int(bytesWritten));
527#endif
528 if (!flushed || bytesWritten != qint64(data.size()))
529 status = QTextStream::WriteFailed;
530}
531
532QString QTextStreamPrivate::read(qsizetype maxlen)
533{
534 QString ret;
535 if (string) {
536 lastTokenSize = qMin(maxlen, string->size() - stringOffset);
537 ret = string->mid(stringOffset, lastTokenSize);
538 } else {
539 while (readBuffer.size() - readBufferOffset < maxlen && fillReadBuffer()) {}
540 lastTokenSize = qMin(maxlen, readBuffer.size() - readBufferOffset);
541 ret = readBuffer.mid(readBufferOffset, lastTokenSize);
542 }
543 consumeLastToken();
544
545#if defined (QTEXTSTREAM_DEBUG)
546 qDebug("QTextStreamPrivate::read() maxlen = %d, token length = %d",
547 int(maxlen), int(ret.length()));
548#endif
549 return ret;
550}
551
552/*!
553 \internal
554
555 Scans no more than \a maxlen QChars in the current buffer for the
556 first \a delimiter. Stores a pointer to the start offset of the
557 token in \a ptr, and the length in QChars in \a length.
558*/
559bool QTextStreamPrivate::scan(const QChar **ptr, qsizetype *length, qsizetype maxlen,
560 TokenDelimiter delimiter)
561{
562 qsizetype totalSize = 0;
563 qsizetype delimSize = 0;
564 bool consumeDelimiter = false;
565 bool foundToken = false;
566 qsizetype startOffset = device ? readBufferOffset : stringOffset;
567 QChar lastChar;
568
569 do {
570 qsizetype endOffset;
571 const QChar *chPtr;
572 if (device) {
573 chPtr = readBuffer.constData();
574 endOffset = readBuffer.size();
575 } else {
576 chPtr = string->constData();
577 endOffset = string->size();
578 }
579 chPtr += startOffset;
580
581 for (; !foundToken && startOffset < endOffset && (!maxlen || totalSize < maxlen); ++startOffset) {
582 const QChar ch = *chPtr++;
583 ++totalSize;
584
585 switch (delimiter) {
586 case Space:
587 if (ch.isSpace()) {
588 foundToken = true;
589 delimSize = 1;
590 }
591 break;
592 case NotSpace:
593 if (!ch.isSpace()) {
594 foundToken = true;
595 delimSize = 1;
596 }
597 break;
598 case EndOfLine:
599 if (ch == u'\n') {
600 foundToken = true;
601 delimSize = (lastChar == u'\r') ? 2 : 1;
602 consumeDelimiter = true;
603 }
604 lastChar = ch;
605 break;
606 }
607 }
608 } while (!foundToken
609 && (!maxlen || totalSize < maxlen)
610 && device && fillReadBuffer());
611
612 if (totalSize == 0) {
613#if defined (QTEXTSTREAM_DEBUG)
614 qDebug("QTextStreamPrivate::scan() reached the end of input.");
615#endif
616 return false;
617 }
618
619 // if we find a '\r' at the end of the data when reading lines,
620 // don't make it part of the line.
621 if (delimiter == EndOfLine && totalSize > 0 && !foundToken) {
622 if (((string && stringOffset + totalSize == string->size()) || (device && device->atEnd()))
623 && lastChar == u'\r') {
624 consumeDelimiter = true;
625 ++delimSize;
626 }
627 }
628
629 // set the read offset and length of the token
630 if (length)
631 *length = totalSize - delimSize;
632 if (ptr)
633 *ptr = readPtr();
634
635 // update last token size. the callee will call consumeLastToken() when
636 // done.
637 lastTokenSize = totalSize;
638 if (!consumeDelimiter)
639 lastTokenSize -= delimSize;
640
641#if defined (QTEXTSTREAM_DEBUG)
642 qDebug("QTextStreamPrivate::scan(%p, %p, %d, %x) token length = %d, delimiter = %d",
643 ptr, length, int(maxlen), uint(delimiter), int(totalSize - delimSize), int(delimSize));
644#endif
645 return true;
646}
647
648/*!
649 \internal
650*/
651inline const QChar *QTextStreamPrivate::readPtr() const
652{
653 Q_ASSERT(readBufferOffset <= readBuffer.size());
654 if (string)
655 return string->constData() + stringOffset;
656 return readBuffer.constData() + readBufferOffset;
657}
658
659/*!
660 \internal
661*/
662inline void QTextStreamPrivate::consumeLastToken()
663{
664 if (lastTokenSize)
665 consume(lastTokenSize);
666 lastTokenSize = 0;
667}
668
669/*!
670 \internal
671*/
672inline void QTextStreamPrivate::consume(qsizetype size)
673{
674#if defined (QTEXTSTREAM_DEBUG)
675 qDebug("QTextStreamPrivate::consume(%d)", int(size));
676#endif
677 if (string) {
678 stringOffset += size;
679 if (stringOffset > string->size())
680 stringOffset = string->size();
681 } else {
682 readBufferOffset += size;
683 if (readBufferOffset >= readBuffer.size()) {
684 readBufferOffset = 0;
685 readBuffer.clear();
686 saveConverterState(device->pos());
687 } else if (readBufferOffset > QTEXTSTREAM_BUFFERSIZE) {
688 readBuffer = readBuffer.remove(0,readBufferOffset);
689 readConverterSavedStateOffset += readBufferOffset;
690 readBufferOffset = 0;
691 }
692 }
693}
694
695/*!
696 \internal
697*/
698inline void QTextStreamPrivate::saveConverterState(qint64 newPos)
699{
700 // ### Hack, FIXME
701 memcpy((void *)&savedToUtf16, (void *)&toUtf16, sizeof(QStringDecoder));
702 readBufferStartDevicePos = newPos;
703 readConverterSavedStateOffset = 0;
704}
705
706/*!
707 \internal
708*/
709inline void QTextStreamPrivate::restoreToSavedConverterState()
710{
711 if (savedToUtf16.isValid())
712 memcpy((void *)&toUtf16, (void *)&savedToUtf16, sizeof(QStringDecoder));
713 else
714 toUtf16.resetState();
715 savedToUtf16 = QStringDecoder();
716}
717
718/*!
719 \internal
720*/
721template <typename Appendable>
722void QTextStreamPrivate::writeImpl(Appendable s)
723{
724 if (string) {
725 // ### What about seek()??
726 string->append(s);
727 } else {
728 writeBuffer.append(s);
729 if (writeBuffer.size() > QTEXTSTREAM_BUFFERSIZE)
730 flushWriteBuffer();
731 }
732}
733
734/*!
735 \internal
736*/
737void QTextStreamPrivate::write(QStringView s)
738{
739 writeImpl(s);
740}
741
742/*!
743 \internal
744*/
745void QTextStreamPrivate::write(QChar ch)
746{
747 writeImpl(ch);
748}
749
750/*!
751 \internal
752*/
753void QTextStreamPrivate::write(QLatin1StringView data)
754{
755 writeImpl(data);
756}
757
758/*!
759 \internal
760*/
761void QTextStreamPrivate::writePadding(qsizetype len)
762{
763 if (string) {
764 // ### What about seek()??
765 string->resize(string->size() + len, params.padChar);
766 } else {
767 writeBuffer.resize(writeBuffer.size() + len, params.padChar);
768 if (writeBuffer.size() > QTEXTSTREAM_BUFFERSIZE)
769 flushWriteBuffer();
770 }
771}
772
773/*!
774 \internal
775*/
776inline bool QTextStreamPrivate::getChar(QChar *ch)
777{
778 if ((string && stringOffset == string->size())
779 || (device && readBuffer.isEmpty() && !fillReadBuffer())) {
780 if (ch)
781 *ch = QChar();
782 return false;
783 }
784 if (ch)
785 *ch = *readPtr();
786 consume(1);
787 return true;
788}
789
790/*!
791 \internal
792*/
793inline void QTextStreamPrivate::ungetChar(QChar ch)
794{
795 if (string) {
796 if (stringOffset == 0)
797 string->prepend(ch);
798 else
799 (*string)[--stringOffset] = ch;
800 return;
801 }
802
803 if (readBufferOffset == 0) {
804 readBuffer.prepend(ch);
805 return;
806 }
807
808 readBuffer[--readBufferOffset] = ch;
809}
810
811/*!
812 \internal
813*/
814inline void QTextStreamPrivate::putChar(QChar ch)
815{
816 if (params.fieldWidth > 0)
817 putString(QStringView{&ch, 1});
818 else
819 write(ch);
820}
821
822
823/*!
824 \internal
825*/
826QTextStreamPrivate::PaddingResult QTextStreamPrivate::padding(qsizetype len) const
827{
828 Q_ASSERT(params.fieldWidth > len); // calling padding() when no padding is needed is an error
829
830 qsizetype left = 0, right = 0;
831
832 const qsizetype padSize = params.fieldWidth - len;
833
834 switch (params.fieldAlignment) {
835 case QTextStream::AlignLeft:
836 right = padSize;
837 break;
838 case QTextStream::AlignRight:
839 case QTextStream::AlignAccountingStyle:
840 left = padSize;
841 break;
842 case QTextStream::AlignCenter:
843 left = padSize/2;
844 right = padSize - padSize/2;
845 break;
846 }
847 return { left, right };
848}
849
850namespace {
851template <typename StringView>
852auto parseSign(StringView data, const QLocale &loc)
853{
854 struct R {
855 StringView sign, rest;
856 explicit operator bool() const noexcept { return !sign.isEmpty(); }
857 };
858 // This assumes that the size in UTF-16 (return value of QLocale functions)
859 // and StringView is the same; in particular, it doesn't work for UTF-8!
860 if (const QString sign = loc.negativeSign(); data.startsWith(sign))
861 return R{data.first(sign.size()), data.sliced(sign.size())};
862 if (const QString sign = loc.positiveSign(); data.startsWith(sign))
863 return R{data.first(sign.size()), data.sliced(sign.size())};
864 return R{nullptr, data};
865}
866} // unnamed namespace
867
868/*!
869 \internal
870*/
871template <typename StringView>
872void QTextStreamPrivate::putStringImpl(StringView data, PutStringMode mode)
873{
874 const bool number = mode == PutStringMode::Number;
875 if (Q_UNLIKELY(params.fieldWidth > data.size())) {
876
877 // handle padding:
878
879 const PaddingResult pad = padding(data.size());
880
881 if (params.fieldAlignment == QTextStream::AlignAccountingStyle && number) {
882 if (const auto r = parseSign(data, locale)) {
883 // write the sign before the padding, then skip it later
884 write(r.sign);
885 data = r.rest;
886 }
887 }
888
889 writePadding(pad.left);
890 write(data);
891 writePadding(pad.right);
892 } else {
893 write(data);
894 }
895}
896
897/*!
898 \internal
899*/
900void QTextStreamPrivate::putString(QLatin1StringView data, PutStringMode mode)
901{
902 putStringImpl(data, mode);
903}
904
905/*!
906 \internal
907*/
908void QTextStreamPrivate::putString(QStringView data, PutStringMode mode)
909{
910 putStringImpl(data, mode);
911}
912
913/*!
914 \internal
915*/
916void QTextStreamPrivate::putString(QUtf8StringView data, PutStringMode mode)
917{
918 putString(data.toString(), mode);
919}
920
921/*!
922 Constructs a QTextStream. Before you can use it for reading or
923 writing, you must assign a device or a string.
924
925 \sa setDevice(), setString()
926*/
927QTextStream::QTextStream()
928 : d_ptr(new QTextStreamPrivate(this))
929{
930#if defined (QTEXTSTREAM_DEBUG)
931 qDebug("QTextStream::QTextStream()");
932#endif
933 Q_D(QTextStream);
934 d->status = Ok;
935}
936
937/*!
938 Constructs a QTextStream that operates on \a device.
939*/
940QTextStream::QTextStream(QIODevice *device)
941 : d_ptr(new QTextStreamPrivate(this))
942{
943#if defined (QTEXTSTREAM_DEBUG)
944 qDebug("QTextStream::QTextStream(QIODevice *device == *%p)",
945 device);
946#endif
947 Q_D(QTextStream);
948 d->device = device;
949 d->setupDevice(device);
950 d->status = Ok;
951}
952
953/*!
954 Constructs a QTextStream that operates on \a string, using \a
955 openMode to define the open mode.
956*/
957QTextStream::QTextStream(QString *string, OpenMode openMode)
958 : d_ptr(new QTextStreamPrivate(this))
959{
960#if defined (QTEXTSTREAM_DEBUG)
961 qDebug("QTextStream::QTextStream(QString *string == *%p, openMode = %d)",
962 string, int(openMode.toInt()));
963#endif
964 Q_D(QTextStream);
965 d->string = string;
966 d->stringOpenMode = openMode;
967 d->status = Ok;
968}
969
970#ifndef QT_BOOTSTRAPPED
971/*!
972 Constructs a QTextStream that operates on \a array, using \a
973 openMode to define the open mode. Internally, the array is wrapped
974 by a QBuffer.
975*/
976QTextStream::QTextStream(QByteArray *array, OpenMode openMode)
977 : d_ptr(new QTextStreamPrivate(this))
978{
979#if defined (QTEXTSTREAM_DEBUG)
980 qDebug("QTextStream::QTextStream(QByteArray *array == *%p, openMode = %d)",
981 array, int(openMode.toInt()));
982#endif
983 Q_D(QTextStream);
984 d->device = new QBuffer(array);
985 d->device->open(openMode);
986 d->deleteDevice = true;
987 d->setupDevice(d->device);
988 d->status = Ok;
989}
990
991/*!
992 Constructs a QTextStream that operates on \a array, using \a
993 openMode to define the open mode. The array is accessed as
994 read-only, regardless of the values in \a openMode.
995
996 This constructor is convenient for working on constant
997 strings. Example:
998
999 \snippet code/src_corelib_io_qtextstream.cpp 3
1000*/
1001QTextStream::QTextStream(const QByteArray &array, OpenMode openMode)
1002 : d_ptr(new QTextStreamPrivate(this))
1003{
1004#if defined (QTEXTSTREAM_DEBUG)
1005 qDebug("QTextStream::QTextStream(const QByteArray &array == *(%p), openMode = %d)",
1006 &array, int(openMode.toInt()));
1007#endif
1008 QBuffer *buffer = new QBuffer;
1009 buffer->setData(array);
1010 buffer->open(openMode);
1011
1012 Q_D(QTextStream);
1013 d->device = buffer;
1014 d->deleteDevice = true;
1015 d->setupDevice(d->device);
1016 d->status = Ok;
1017}
1018#endif
1019
1020/*!
1021 Constructs a QTextStream that operates on \a fileHandle, using \a
1022 openMode to define the open mode. Internally, a QFile is created
1023 to handle the FILE pointer.
1024
1025 This constructor is useful for working directly with the common
1026 FILE based input and output streams: stdin, stdout and stderr. Example:
1027
1028 \snippet code/src_corelib_io_qtextstream.cpp 4
1029*/
1030
1031QTextStream::QTextStream(FILE *fileHandle, OpenMode openMode)
1032 : d_ptr(new QTextStreamPrivate(this))
1033{
1034#if defined (QTEXTSTREAM_DEBUG)
1035 qDebug("QTextStream::QTextStream(FILE *fileHandle = %p, openMode = %d)",
1036 fileHandle, int(openMode.toInt()));
1037#endif
1038 QFile *file = new QFile;
1039 // Discarding the return value of open; even if it failed
1040 // (and the file is not open), QTextStream still reports `Ok`
1041 // for closed QIODevices, so there's nothing really to do here.
1042 (void)file->open(fileHandle, openMode);
1043
1044 Q_D(QTextStream);
1045 d->device = file;
1046 d->deleteDevice = true;
1047 d->setupDevice(d->device);
1048 d->status = Ok;
1049}
1050
1051/*!
1052 Destroys the QTextStream.
1053
1054 If the stream operates on a device, flush() will be called
1055 implicitly. Otherwise, the device is unaffected.
1056*/
1057QTextStream::~QTextStream()
1058{
1059 Q_D(QTextStream);
1060#if defined (QTEXTSTREAM_DEBUG)
1061 qDebug("QTextStream::~QTextStream()");
1062#endif
1063 if (!d->writeBuffer.isEmpty())
1064 d->flushWriteBuffer();
1065}
1066
1067/*!
1068 Resets QTextStream's formatting options, bringing it back to its
1069 original constructed state. The device, string and any buffered
1070 data is left untouched.
1071*/
1072void QTextStream::reset()
1073{
1074 Q_D(QTextStream);
1075
1076 d->params.reset();
1077}
1078
1079/*!
1080 Flushes any buffered data waiting to be written to the device.
1081
1082 If QTextStream operates on a string, this function does nothing.
1083*/
1084void QTextStream::flush()
1085{
1086 Q_D(QTextStream);
1087 d->flushWriteBuffer();
1088}
1089
1090/*!
1091 Seeks to the position \a pos in the device. Returns \c true on
1092 success; otherwise returns \c false.
1093*/
1094bool QTextStream::seek(qint64 pos)
1095{
1096 Q_D(QTextStream);
1097 d->lastTokenSize = 0;
1098
1099 if (d->device) {
1100 // Empty the write buffer
1101 d->flushWriteBuffer();
1102 if (!d->device->seek(pos))
1103 return false;
1104 d->resetReadBuffer();
1105
1106 d->toUtf16.resetState();
1107 d->fromUtf16.resetState();
1108 return true;
1109 }
1110
1111 // string
1112 if (d->string && pos <= d->string->size()) {
1113 d->stringOffset = pos;
1114 return true;
1115 }
1116 return false;
1117}
1118
1119/*!
1120 \since 4.2
1121
1122 Returns the device position corresponding to the current position of the
1123 stream, or -1 if an error occurs (e.g., if there is no device or string,
1124 or if there's a device error).
1125
1126 Because QTextStream is buffered, this function may have to
1127 seek the device to reconstruct a valid device position. This
1128 operation can be expensive, so you may want to avoid calling this
1129 function in a tight loop.
1130
1131 \sa seek()
1132*/
1133qint64 QTextStream::pos() const
1134{
1135 Q_D(const QTextStream);
1136 if (d->device) {
1137 // Cutoff
1138 if (d->readBuffer.isEmpty())
1139 return d->device->pos();
1140 if (d->device->isSequential())
1141 return 0;
1142
1143 // Seek the device
1144 if (!d->device->seek(d->readBufferStartDevicePos))
1145 return qint64(-1);
1146
1147 // Reset the read buffer
1148 QTextStreamPrivate *thatd = const_cast<QTextStreamPrivate *>(d);
1149 thatd->readBuffer.clear();
1150
1151 thatd->restoreToSavedConverterState();
1152 if (d->readBufferStartDevicePos == 0)
1153 thatd->autoDetectUnicode = true;
1154
1155 // Rewind the device to get to the current position Ensure that
1156 // readBufferOffset is unaffected by fillReadBuffer()
1157 qsizetype oldReadBufferOffset = d->readBufferOffset + d->readConverterSavedStateOffset;
1158 while (d->readBuffer.size() < oldReadBufferOffset) {
1159 if (!thatd->fillReadBuffer(1))
1160 return qint64(-1);
1161 }
1162 thatd->readBufferOffset = oldReadBufferOffset;
1163 thatd->readConverterSavedStateOffset = 0;
1164
1165 // Return the device position.
1166 return d->device->pos();
1167 }
1168
1169 if (d->string)
1170 return d->stringOffset;
1171
1172 qWarning("QTextStream::pos: no device");
1173 return qint64(-1);
1174}
1175
1176/*!
1177 Reads and discards whitespace from the stream until either a
1178 non-space character is detected, or until atEnd() returns
1179 true. This function is useful when reading a stream character by
1180 character.
1181
1182 Whitespace characters are all characters for which
1183 QChar::isSpace() returns \c true.
1184
1185 \sa operator>>()
1186*/
1187void QTextStream::skipWhiteSpace()
1188{
1189 Q_D(QTextStream);
1191 d->scan(nullptr, nullptr, 0, QTextStreamPrivate::NotSpace);
1192 d->consumeLastToken();
1193}
1194
1195/*!
1196 Sets the current device to \a device. If a device has already been
1197 assigned, QTextStream will call flush() before the old device is
1198 replaced.
1199
1200 \note This function resets locale to the default locale ('C')
1201 and encoding to the default encoding, UTF-8.
1202
1203 \sa device(), setString()
1204*/
1205void QTextStream::setDevice(QIODevice *device)
1206{
1207 Q_D(QTextStream);
1208 flush();
1209 if (d->deleteDevice) {
1210 d->disconnectFromDevice();
1211 delete d->device;
1212 d->deleteDevice = false;
1213 }
1214
1215 d->reset();
1216 d->status = Ok;
1217 d->device = device;
1218 d->resetReadBuffer();
1219 d->setupDevice(d->device);
1220}
1221
1222/*!
1223 Returns the current device associated with the QTextStream,
1224 or \nullptr if no device has been assigned.
1225
1226 \sa setDevice(), string()
1227*/
1228QIODevice *QTextStream::device() const
1229{
1230 Q_D(const QTextStream);
1231 return d->device;
1232}
1233
1234/*!
1235 Sets the current string to \a string, using the given \a
1236 openMode. If a device has already been assigned, QTextStream will
1237 call flush() before replacing it.
1238
1239 \sa string(), setDevice()
1240*/
1241void QTextStream::setString(QString *string, OpenMode openMode)
1242{
1243 Q_D(QTextStream);
1244 flush();
1245 if (d->deleteDevice) {
1246#ifndef QT_NO_QOBJECT
1247 d->setupDevice(d->device);
1248 d->device->blockSignals(true);
1249#endif
1250 delete d->device;
1251 d->deleteDevice = false;
1252 }
1253
1254 d->reset();
1255 d->status = Ok;
1256 d->string = string;
1257 d->stringOpenMode = openMode;
1258}
1259
1260/*!
1261 Returns the current string assigned to the QTextStream, or
1262 \nullptr if no string has been assigned.
1263
1264 \sa setString(), device()
1265*/
1266QString *QTextStream::string() const
1267{
1268 Q_D(const QTextStream);
1269 return d->string;
1270}
1271
1272/*!
1273 Sets the field alignment to \a mode. When used together with
1274 setFieldWidth(), this function allows you to generate formatted
1275 output with text aligned to the left, to the right or center
1276 aligned.
1277
1278 \sa fieldAlignment(), setFieldWidth()
1279*/
1280void QTextStream::setFieldAlignment(FieldAlignment mode)
1281{
1282 Q_D(QTextStream);
1283 d->params.fieldAlignment = mode;
1284}
1285
1286/*!
1287 Returns the current field alignment.
1288
1289 \sa setFieldAlignment(), fieldWidth()
1290*/
1291QTextStream::FieldAlignment QTextStream::fieldAlignment() const
1292{
1293 Q_D(const QTextStream);
1294 return d->params.fieldAlignment;
1295}
1296
1297/*!
1298 Sets the pad character to \a ch. The default value is the ASCII
1299 space character (' '), or QChar(0x20). This character is used to
1300 fill in the space in fields when generating text.
1301
1302 Example:
1303
1304 \snippet code/src_corelib_io_qtextstream.cpp 5
1305
1306 The string \c s contains:
1307
1308 \snippet code/src_corelib_io_qtextstream.cpp 6
1309
1310 \sa padChar(), setFieldWidth()
1311*/
1312void QTextStream::setPadChar(QChar ch)
1313{
1314 Q_D(QTextStream);
1315 d->params.padChar = ch;
1316}
1317
1318/*!
1319 Returns the current pad character.
1320
1321 \sa setPadChar(), setFieldWidth()
1322*/
1323QChar QTextStream::padChar() const
1324{
1325 Q_D(const QTextStream);
1326 return d->params.padChar;
1327}
1328
1329/*!
1330 Sets the current field width to \a width. If \a width is 0 (the
1331 default), the field width is equal to the length of the generated
1332 text.
1333
1334 \note The field width applies to every element appended to this
1335 stream after this function has been called (e.g., it also pads
1336 endl). This behavior is different from similar classes in the STL,
1337 where the field width only applies to the next element.
1338
1339 \sa fieldWidth(), setPadChar()
1340*/
1341void QTextStream::setFieldWidth(int width)
1342{
1343 Q_D(QTextStream);
1344 d->params.fieldWidth = width;
1345}
1346
1347/*!
1348 Returns the current field width.
1349
1350 \sa setFieldWidth()
1351*/
1352int QTextStream::fieldWidth() const
1353{
1354 Q_D(const QTextStream);
1355 return d->params.fieldWidth;
1356}
1357
1358/*!
1359 Sets the current number flags to \a flags. \a flags is a set of
1360 flags from the NumberFlag enum, and describes options for
1361 formatting generated code (e.g., whether or not to always write
1362 the base or sign of a number).
1363
1364 \sa numberFlags(), setIntegerBase(), setRealNumberNotation()
1365*/
1366void QTextStream::setNumberFlags(NumberFlags flags)
1367{
1368 Q_D(QTextStream);
1369 d->params.numberFlags = flags;
1370}
1371
1372/*!
1373 Returns the current number flags.
1374
1375 \sa setNumberFlags(), integerBase(), realNumberNotation()
1376*/
1377QTextStream::NumberFlags QTextStream::numberFlags() const
1378{
1379 Q_D(const QTextStream);
1380 return d->params.numberFlags;
1381}
1382
1383/*!
1384 Sets the base of integers to \a base, both for reading and for
1385 generating numbers. \a base can be either 2 (binary), 8 (octal),
1386 10 (decimal) or 16 (hexadecimal). If \a base is 0, QTextStream
1387 will attempt to detect the base by inspecting the data on the
1388 stream. When generating numbers, QTextStream assumes base is 10
1389 unless the base has been set explicitly.
1390
1391 \sa integerBase(), QString::number(), setNumberFlags()
1392*/
1393void QTextStream::setIntegerBase(int base)
1394{
1395 Q_D(QTextStream);
1396 d->params.integerBase = base;
1397}
1398
1399/*!
1400 Returns the current base of integers. 0 means that the base is
1401 detected when reading, or 10 (decimal) when generating numbers.
1402
1403 \sa setIntegerBase(), QString::number(), numberFlags()
1404*/
1405int QTextStream::integerBase() const
1406{
1407 Q_D(const QTextStream);
1408 return d->params.integerBase;
1409}
1410
1411/*!
1412 Sets the real number notation to \a notation (SmartNotation,
1413 FixedNotation, ScientificNotation). When reading and generating
1414 numbers, QTextStream uses this value to detect the formatting of
1415 real numbers.
1416
1417 \sa realNumberNotation(), setRealNumberPrecision(), setNumberFlags(), setIntegerBase()
1418*/
1419void QTextStream::setRealNumberNotation(RealNumberNotation notation)
1420{
1421 Q_D(QTextStream);
1422 d->params.realNumberNotation = notation;
1423}
1424
1425/*!
1426 Returns the current real number notation.
1427
1428 \sa setRealNumberNotation(), realNumberPrecision(), numberFlags(), integerBase()
1429*/
1430QTextStream::RealNumberNotation QTextStream::realNumberNotation() const
1431{
1432 Q_D(const QTextStream);
1433 return d->params.realNumberNotation;
1434}
1435
1436/*!
1437 Sets the precision of real numbers to \a precision. This value
1438 describes the number of fraction digits QTextStream should
1439 write when generating real numbers (FixedNotation, ScientificNotation), or
1440 the maximum number of significant digits (SmartNotation).
1441
1442 The precision cannot be a negative value. The default value is 6.
1443
1444 \sa realNumberPrecision(), setRealNumberNotation()
1445*/
1446void QTextStream::setRealNumberPrecision(int precision)
1447{
1448 Q_D(QTextStream);
1449 if (precision < 0) {
1450 qWarning("QTextStream::setRealNumberPrecision: Invalid precision (%d)", precision);
1451 d->params.realNumberPrecision = 6;
1452 return;
1453 }
1454 d->params.realNumberPrecision = precision;
1455}
1456
1457/*!
1458 Returns the current real number precision, or the number of fraction
1459 digits QTextStream will write when generating real numbers
1460 (FixedNotation, ScientificNotation), or the maximum number of significant
1461 digits (SmartNotation).
1462
1463 \sa setRealNumberNotation(), realNumberNotation(), numberFlags(), integerBase()
1464*/
1465int QTextStream::realNumberPrecision() const
1466{
1467 Q_D(const QTextStream);
1468 return d->params.realNumberPrecision;
1469}
1470
1471/*!
1472 Returns the status of the text stream.
1473
1474 \sa QTextStream::Status, setStatus(), resetStatus()
1475*/
1476
1477QTextStream::Status QTextStream::status() const
1478{
1479 Q_D(const QTextStream);
1480 return d->status;
1481}
1482
1483/*!
1484 \since 4.1
1485
1486 Resets the status of the text stream.
1487
1488 \sa QTextStream::Status, status(), setStatus()
1489*/
1490void QTextStream::resetStatus()
1491{
1492 Q_D(QTextStream);
1493 d->status = Ok;
1494}
1495
1496/*!
1497 \since 4.1
1498
1499 Sets the status of the text stream to the \a status given.
1500
1501 Subsequent calls to setStatus() are ignored until resetStatus()
1502 is called.
1503
1504 \sa Status, status(), resetStatus()
1505*/
1506void QTextStream::setStatus(Status status)
1507{
1508 Q_D(QTextStream);
1509 if (d->status == Ok)
1510 d->status = status;
1511}
1512
1513/*!
1514 Returns \c true if there is no more data to be read from the
1515 QTextStream; otherwise returns \c false. This is similar to, but not
1516 the same as calling QIODevice::atEnd(), as QTextStream also takes
1517 into account its internal Unicode buffer.
1518*/
1519bool QTextStream::atEnd() const
1520{
1521 Q_D(const QTextStream);
1522 CHECK_VALID_STREAM(true);
1523
1524 if (d->string)
1525 return d->string->size() == d->stringOffset;
1526 return d->readBuffer.isEmpty() && d->device->atEnd();
1527}
1528
1529/*!
1530 Reads the entire content of the stream, and returns it as a
1531 QString. Avoid this function when working on large files, as it
1532 will consume a significant amount of memory.
1533
1534 Calling \l {QTextStream::readLine()}{readLine()} is better if you do not know how much data is
1535 available.
1536
1537 \sa readLine()
1538*/
1539QString QTextStream::readAll()
1540{
1541 Q_D(QTextStream);
1542 CHECK_VALID_STREAM(QString());
1543
1544 return d->read(std::numeric_limits<qsizetype>::max());
1545}
1546
1547/*!
1548 Reads one line of text from the stream, and returns it as a
1549 QString. The maximum allowed line length is set to \a maxlen. If
1550 the stream contains lines longer than this, then the lines will be
1551 split after \a maxlen characters and returned in parts.
1552
1553 If \a maxlen is 0, the lines can be of any length.
1554
1555 The returned line has no trailing end-of-line characters ("\\n"
1556 or "\\r\\n"), so calling QString::trimmed() can be unnecessary.
1557
1558 If the stream has read to the end of the file, \l {QTextStream::readLine()}{readLine()}
1559 will return a null QString. For strings, or for devices that support it,
1560 you can explicitly test for the end of the stream using atEnd().
1561
1562 \sa readAll(), QIODevice::readLine()
1563*/
1564QString QTextStream::readLine(qint64 maxlen)
1565{
1566 QString line;
1567
1568 readLineInto(&line, maxlen);
1569 return line;
1570}
1571
1572/*!
1573 \since 5.5
1574
1575 Reads one line of text from the stream into \a line.
1576 If \a line is \nullptr, the read line is not stored.
1577
1578 The maximum allowed line length is set to \a maxlen. If
1579 the stream contains lines longer than this, then the lines will be
1580 split after \a maxlen characters and returned in parts.
1581
1582 If \a maxlen is 0, the lines can be of any length.
1583
1584 The resulting line has no trailing end-of-line characters ("\\n"
1585 or "\\r\\n"), so calling QString::trimmed() can be unnecessary.
1586
1587 If \a line has sufficient capacity for the data that is about to be
1588 read, this function may not need to allocate new memory. Because of
1589 this, it can be faster than readLine().
1590
1591 Returns \c false if the stream has read to the end of the file or
1592 an error has occurred; otherwise returns \c true. The contents in
1593 \a line before the call are discarded in any case.
1594
1595 \sa readAll(), QIODevice::readLine(), QIODevice::readLineInto()
1596*/
1597bool QTextStream::readLineInto(QString *line, qint64 maxlen)
1598{
1599 Q_D(QTextStream);
1600 // keep in sync with CHECK_VALID_STREAM
1601 if (!d->string && !d->device) {
1602 qWarning("QTextStream: No device");
1603 if (line && !line->isNull())
1604 line->resize(0);
1605 return false;
1606 }
1607
1608 const QChar *readPtr;
1609 qsizetype length;
1610 if (!d->scan(&readPtr, &length, qsizetype(maxlen), QTextStreamPrivate::EndOfLine)) {
1611 if (line && !line->isNull())
1612 line->resize(0);
1613 return false;
1614 }
1615
1616 if (Q_LIKELY(line))
1617 line->setUnicode(readPtr, length);
1618 d->consumeLastToken();
1619 return true;
1620}
1621
1622/*!
1623 \since 4.1
1624
1625 Reads at most \a maxlen characters from the stream, and returns the data
1626 read as a QString.
1627
1628 \sa readAll(), readLine(), QIODevice::read()
1629*/
1630QString QTextStream::read(qint64 maxlen)
1631{
1632 Q_D(QTextStream);
1633 CHECK_VALID_STREAM(QString());
1634
1635 if (maxlen <= 0)
1636 return QString::fromLatin1(""); // empty, not null
1637
1638 return d->read(q26::saturate_cast<qsizetype>(maxlen));
1639}
1640
1641/*!
1642 \internal
1643*/
1644QTextStreamPrivate::NumberParsingStatus QTextStreamPrivate::getNumber(qulonglong *ret)
1645{
1646 scan(nullptr, nullptr, 0, NotSpace);
1647 consumeLastToken();
1648
1649 // detect integer encoding
1650 int base = params.integerBase;
1651 if (base == 0) {
1652 QChar ch;
1653 if (!getChar(&ch))
1654 return npsInvalidPrefix;
1655 if (ch == u'0') {
1656 QChar ch2;
1657 if (!getChar(&ch2)) {
1658 // Result is the number 0
1659 *ret = 0;
1660 return npsOk;
1661 }
1662 ch2 = ch2.toLower();
1663
1664 if (ch2 == u'x') {
1665 base = 16;
1666 } else if (ch2 == u'b') {
1667 base = 2;
1668 } else if (ch2.isDigit() && ch2.digitValue() >= 0 && ch2.digitValue() <= 7) {
1669 base = 8;
1670 } else {
1671 base = 10;
1672 }
1673 ungetChar(ch2);
1674 } else if (ch == locale.negativeSign() || ch == locale.positiveSign() || ch.isDigit()) {
1675 base = 10;
1676 } else {
1677 ungetChar(ch);
1678 return npsInvalidPrefix;
1679 }
1680 ungetChar(ch);
1681 // State of the stream is now the same as on entry
1682 // (cursor is at prefix),
1683 // and local variable 'base' has been set appropriately.
1684 }
1685
1686 qulonglong val=0;
1687 switch (base) {
1688 case 2: {
1689 QChar pf1, pf2, dig;
1690 // Parse prefix '0b'
1691 if (!getChar(&pf1) || pf1 != u'0')
1692 return npsInvalidPrefix;
1693 if (!getChar(&pf2) || pf2.toLower() != u'b')
1694 return npsInvalidPrefix;
1695 // Parse digits
1696 qsizetype ndigits = 0;
1697 while (getChar(&dig)) {
1698 char16_t n = dig.toLower().unicode();
1699 if (n == u'0' || n == u'1') {
1700 val <<= 1;
1701 val += n - u'0';
1702 } else {
1703 ungetChar(dig);
1704 break;
1705 }
1706 ndigits++;
1707 }
1708 if (ndigits == 0) {
1709 // Unwind the prefix and abort
1710 ungetChar(pf2);
1711 ungetChar(pf1);
1712 return npsMissingDigit;
1713 }
1714 break;
1715 }
1716 case 8: {
1717 QChar pf, dig;
1718 // Parse prefix u'0'
1719 if (!getChar(&pf) || pf != u'0')
1720 return npsInvalidPrefix;
1721 // Parse digits
1722 qsizetype ndigits = 0;
1723 while (getChar(&dig)) {
1724 char16_t n = dig.toLower().unicode();
1725 if (isOctalDigit(n)) {
1726 val *= 8;
1727 val += n - u'0';
1728 } else {
1729 ungetChar(dig);
1730 break;
1731 }
1732 ndigits++;
1733 }
1734 if (ndigits == 0) {
1735 // Unwind the prefix and abort
1736 ungetChar(pf);
1737 return npsMissingDigit;
1738 }
1739 break;
1740 }
1741 case 10: {
1742 // Parse sign (or first digit)
1743 QChar sign;
1744 qsizetype ndigits = 0;
1745 if (!getChar(&sign))
1746 return npsMissingDigit;
1747 if (sign != locale.negativeSign() && sign != locale.positiveSign()) {
1748 if (!sign.isDigit()) {
1749 ungetChar(sign);
1750 return npsMissingDigit;
1751 }
1752 val += sign.digitValue();
1753 ndigits++;
1754 }
1755 // Parse digits
1756 QChar ch;
1757 while (getChar(&ch)) {
1758 if (ch.isDigit()) {
1759 val *= 10;
1760 val += ch.digitValue();
1761 } else if (locale != QLocale::c() && ch == locale.groupSeparator()) {
1762 continue;
1763 } else {
1764 ungetChar(ch);
1765 break;
1766 }
1767 ndigits++;
1768 }
1769 if (ndigits == 0)
1770 return npsMissingDigit;
1771 if (sign == locale.negativeSign()) {
1772 qlonglong ival = qlonglong(val);
1773 if (ival > 0)
1774 ival = -ival;
1775 val = qulonglong(ival);
1776 }
1777 break;
1778 }
1779 case 16: {
1780 QChar pf1, pf2, dig;
1781 // Parse prefix ' 0x'
1782 if (!getChar(&pf1) || pf1 != u'0')
1783 return npsInvalidPrefix;
1784 if (!getChar(&pf2) || pf2.toLower() != u'x')
1785 return npsInvalidPrefix;
1786 // Parse digits
1787 qsizetype ndigits = 0;
1788 while (getChar(&dig)) {
1789 const int h = fromHex(dig.unicode());
1790 if (h != -1) {
1791 val <<= 4;
1792 val += h;
1793 } else {
1794 ungetChar(dig);
1795 break;
1796 }
1797 ndigits++;
1798 }
1799 if (ndigits == 0) {
1800 return npsMissingDigit;
1801 }
1802 break;
1803 }
1804 default:
1805 // Unsupported integerBase
1806 return npsInvalidPrefix;
1807 }
1808
1809 if (ret)
1810 *ret = val;
1811 return npsOk;
1812}
1813
1814/*!
1815 \internal
1816 (hihi)
1817*/
1818bool QTextStreamPrivate::getReal(double *f)
1819{
1820 // We use a table-driven FSM to parse floating point numbers
1821 // strtod() cannot be used directly since we may be reading from a
1822 // QIODevice.
1823 enum ParserState {
1824 Init = 0,
1825 Sign = 1,
1826 Mantissa = 2,
1827 Dot = 3,
1828 Abscissa = 4,
1829 ExpMark = 5,
1830 ExpSign = 6,
1831 Exponent = 7,
1832 Nan1 = 8,
1833 Nan2 = 9,
1834 Inf1 = 10,
1835 Inf2 = 11,
1836 NanInf = 12,
1837 Done = 13
1838 };
1839 enum InputToken {
1840 None = 0,
1841 InputSign = 1,
1842 InputDigit = 2,
1843 InputDot = 3,
1844 InputExp = 4,
1845 InputI = 5,
1846 InputN = 6,
1847 InputF = 7,
1848 InputA = 8,
1849 InputT = 9
1850 };
1851
1852 static const uchar table[13][10] = {
1853 // None InputSign InputDigit InputDot InputExp InputI InputN InputF InputA InputT
1854 { 0, Sign, Mantissa, Dot, 0, Inf1, Nan1, 0, 0, 0 }, // 0 Init
1855 { 0, 0, Mantissa, Dot, 0, Inf1, Nan1, 0, 0, 0 }, // 1 Sign
1856 { Done, Done, Mantissa, Dot, ExpMark, 0, 0, 0, 0, 0 }, // 2 Mantissa
1857 { 0, 0, Abscissa, 0, 0, 0, 0, 0, 0, 0 }, // 3 Dot
1858 { Done, Done, Abscissa, Done, ExpMark, 0, 0, 0, 0, 0 }, // 4 Abscissa
1859 { 0, ExpSign, Exponent, 0, 0, 0, 0, 0, 0, 0 }, // 5 ExpMark
1860 { 0, 0, Exponent, 0, 0, 0, 0, 0, 0, 0 }, // 6 ExpSign
1861 { Done, Done, Exponent, Done, Done, 0, 0, 0, 0, 0 }, // 7 Exponent
1862 { 0, 0, 0, 0, 0, 0, 0, 0, Nan2, 0 }, // 8 Nan1
1863 { 0, 0, 0, 0, 0, 0, NanInf, 0, 0, 0 }, // 9 Nan2
1864 { 0, 0, 0, 0, 0, 0, Inf2, 0, 0, 0 }, // 10 Inf1
1865 { 0, 0, 0, 0, 0, 0, 0, NanInf, 0, 0 }, // 11 Inf2
1866 { Done, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // 11 NanInf
1867 };
1868
1869 ParserState state = Init;
1870 InputToken input = None;
1871
1872 scan(nullptr, nullptr, 0, NotSpace);
1873 consumeLastToken();
1874
1875 const qsizetype BufferSize = 128;
1876 char buf[BufferSize];
1877 qsizetype i = 0;
1878
1879 QChar c;
1880 while (getChar(&c)) {
1881 switch (c.unicode()) {
1882 case u'0': case u'1': case u'2': case u'3': case u'4':
1883 case u'5': case u'6': case u'7': case u'8': case u'9':
1884 input = InputDigit;
1885 break;
1886 case u'i': case u'I':
1887 input = InputI;
1888 break;
1889 case u'n': case u'N':
1890 input = InputN;
1891 break;
1892 case u'f': case u'F':
1893 input = InputF;
1894 break;
1895 case u'a': case u'A':
1896 input = InputA;
1897 break;
1898 case u't': case u'T':
1899 input = InputT;
1900 break;
1901 default: {
1902 QChar lc = c.toLower();
1903 if (lc == locale.decimalPoint().toLower())
1904 input = InputDot;
1905 else if (lc == locale.exponential().toLower())
1906 input = InputExp;
1907 else if (lc == locale.negativeSign().toLower()
1908 || lc == locale.positiveSign().toLower())
1909 input = InputSign;
1910 else if (locale != QLocale::c() // backward-compatibility
1911 && lc == locale.groupSeparator().toLower())
1912 input = InputDigit; // well, it isn't a digit, but no one cares.
1913 else
1914 input = None;
1915 }
1916 break;
1917 }
1918
1919 state = ParserState(table[state][input]);
1920
1921 if (state == Init || state == Done || i > (BufferSize - 5)) {
1922 ungetChar(c);
1923 if (i > (BufferSize - 5)) { // ignore rest of digits
1924 while (getChar(&c)) {
1925 if (!c.isDigit()) {
1926 ungetChar(c);
1927 break;
1928 }
1929 }
1930 }
1931 break;
1932 }
1933
1934 buf[i++] = c.toLatin1();
1935 }
1936
1937 if (i == 0)
1938 return false;
1939 if (!f)
1940 return true;
1941 buf[i] = '\0';
1942
1943 // backward-compatibility. Old implementation supported +nan/-nan
1944 // for some reason. QLocale only checks for lower-case
1945 // nan/+inf/-inf, so here we also check for uppercase and mixed
1946 // case versions.
1947 if (!qstricmp(buf, "nan") || !qstricmp(buf, "+nan") || !qstricmp(buf, "-nan")) {
1948 *f = qt_qnan();
1949 return true;
1950 } else if (!qstricmp(buf, "+inf") || !qstricmp(buf, "inf")) {
1951 *f = qt_inf();
1952 return true;
1953 } else if (!qstricmp(buf, "-inf")) {
1954 *f = -qt_inf();
1955 return true;
1956 }
1957 bool ok;
1958 *f = locale.toDouble(QString::fromLatin1(buf), &ok);
1959 return ok;
1960}
1961
1962/*!
1963 Reads a character from the stream and stores it in \a c. Returns a
1964 reference to the QTextStream, so several operators can be
1965 nested. Example:
1966
1967 \snippet code/src_corelib_io_qtextstream.cpp 7
1968
1969 Whitespace is \e not skipped.
1970*/
1971
1972QTextStream &QTextStream::operator>>(QChar &c)
1973{
1974 Q_D(QTextStream);
1975 CHECK_VALID_STREAM(*this);
1976 d->scan(nullptr, nullptr, 0, QTextStreamPrivate::NotSpace);
1977 if (!d->getChar(&c))
1978 setStatus(ReadPastEnd);
1979 return *this;
1980}
1981
1982/*!
1983 \overload
1984
1985 Reads a character from the stream and stores it in \a c. The
1986 character from the stream is converted to ISO-8859-1 before it is
1987 stored.
1988
1989 \sa QChar::toLatin1()
1990*/
1991QTextStream &QTextStream::operator>>(char &c)
1992{
1993 QChar ch;
1994 *this >> ch;
1995 c = ch.toLatin1();
1996 return *this;
1997}
1998
1999/*!
2000 \fn QTextStream &QTextStream::operator>>(char16_t &c)
2001 \overload
2002 \since 6.4
2003
2004 Reads a character from the stream and stores it in \a c.
2005*/
2006
2007/*!
2008 Reads an integer from the stream and stores it in \a i, then
2009 returns a reference to the QTextStream. The number is cast to
2010 the correct type before it is stored. If no number was detected on
2011 the stream, \a i is set to 0.
2012
2013 By default, QTextStream will attempt to detect the base of the
2014 number using the following rules:
2015
2016 \table
2017 \header \li Prefix \li Base
2018 \row \li "0b" or "0B" \li 2 (binary)
2019 \row \li "0" followed by "0-7" \li 8 (octal)
2020 \row \li "0" otherwise \li 10 (decimal)
2021 \row \li "0x" or "0X" \li 16 (hexadecimal)
2022 \row \li "1" to "9" \li 10 (decimal)
2023 \endtable
2024
2025 By calling setIntegerBase(), you can specify the integer base
2026 explicitly. This will disable the auto-detection, and speed up
2027 QTextStream slightly.
2028
2029 Leading whitespace is skipped.
2030*/
2031QTextStream &QTextStream::operator>>(signed short &i)
2032{
2034}
2035
2036/*!
2037 \overload
2038
2039 Stores the integer in the unsigned short \a i.
2040*/
2041QTextStream &QTextStream::operator>>(unsigned short &i)
2042{
2044}
2045
2046/*!
2047 \overload
2048
2049 Stores the integer in the signed int \a i.
2050*/
2051QTextStream &QTextStream::operator>>(signed int &i)
2052{
2054}
2055
2056/*!
2057 \overload
2058
2059 Stores the integer in the unsigned int \a i.
2060*/
2061QTextStream &QTextStream::operator>>(unsigned int &i)
2062{
2064}
2065
2066/*!
2067 \overload
2068
2069 Stores the integer in the signed long \a i.
2070*/
2071QTextStream &QTextStream::operator>>(signed long &i)
2072{
2074}
2075
2076/*!
2077 \overload
2078
2079 Stores the integer in the unsigned long \a i.
2080*/
2081QTextStream &QTextStream::operator>>(unsigned long &i)
2082{
2084}
2085
2086/*!
2087 \overload
2088
2089 Stores the integer in the qlonglong \a i.
2090*/
2091QTextStream &QTextStream::operator>>(qlonglong &i)
2092{
2094}
2095
2096/*!
2097 \overload
2098
2099 Stores the integer in the qulonglong \a i.
2100*/
2101QTextStream &QTextStream::operator>>(qulonglong &i)
2102{
2104}
2105
2106/*!
2107 Reads a real number from the stream and stores it in \a f, then
2108 returns a reference to the QTextStream. The number is cast to
2109 the correct type. If no real number is detect on the stream, \a f
2110 is set to 0.0.
2111
2112 As a special exception, QTextStream allows the strings "nan" and "inf" to
2113 represent NAN and INF floats or doubles.
2114
2115 Leading whitespace is skipped.
2116*/
2117QTextStream &QTextStream::operator>>(float &f)
2118{
2120}
2121
2122/*!
2123 \overload
2124
2125 Stores the real number in the double \a f.
2126*/
2127QTextStream &QTextStream::operator>>(double &f)
2128{
2130}
2131
2132/*!
2133 Reads a word from the stream and stores it in \a str, then returns
2134 a reference to the stream. Words are separated by whitespace
2135 (i.e., all characters for which QChar::isSpace() returns \c true).
2136
2137 Leading whitespace is skipped.
2138*/
2139QTextStream &QTextStream::operator>>(QString &str)
2140{
2141 Q_D(QTextStream);
2142 CHECK_VALID_STREAM(*this);
2143
2144 str.clear();
2145 d->scan(nullptr, nullptr, 0, QTextStreamPrivate::NotSpace);
2146 d->consumeLastToken();
2147
2148 const QChar *ptr;
2149 qsizetype length;
2150 if (!d->scan(&ptr, &length, 0, QTextStreamPrivate::Space)) {
2151 setStatus(ReadPastEnd);
2152 return *this;
2153 }
2154
2155 str = QString(ptr, length);
2156 d->consumeLastToken();
2157 return *this;
2158}
2159
2160/*!
2161 \overload
2162
2163 Converts the word to UTF-8, then stores it in \a array.
2164
2165 \sa QString::toLatin1()
2166*/
2167QTextStream &QTextStream::operator>>(QByteArray &array)
2168{
2169 Q_D(QTextStream);
2170 CHECK_VALID_STREAM(*this);
2171
2172 d->scan(nullptr, nullptr, 0, QTextStreamPrivate::NotSpace);
2173 d->consumeLastToken();
2174
2175 const QChar *ptr;
2176 qsizetype length;
2177 if (!d->scan(&ptr, &length, 0, QTextStreamPrivate::Space)) {
2178 setStatus(ReadPastEnd);
2179 array.clear();
2180 return *this;
2181 }
2182
2183 array = QStringView(ptr, length).toUtf8();
2184
2185 d->consumeLastToken();
2186 return *this;
2187}
2188
2189/*!
2190 \overload
2191
2192 Converts the word to UTF-8 and stores it in \a c, terminated by a '\\0'
2193 character. If no word is available, only the '\\0' character is stored.
2194
2195 Warning: Although convenient, this operator is dangerous and must
2196 be used with care. QTextStream assumes that \a c points to a
2197 buffer with enough space to hold the word. If the buffer is too
2198 small, your application may crash. For a word consisting of \c{n} QChars,
2199 the buffer needs to be at least \c{3*n+1} characters long.
2200
2201 If possible, use the QByteArray operator instead.
2202*/
2203QTextStream &QTextStream::operator>>(char *c)
2204{
2205 Q_D(QTextStream);
2206 *c = 0;
2207 CHECK_VALID_STREAM(*this);
2208 d->scan(nullptr, nullptr, 0, QTextStreamPrivate::NotSpace);
2209 d->consumeLastToken();
2210
2211 const QChar *ptr;
2212 qsizetype length;
2213 if (!d->scan(&ptr, &length, 0, QTextStreamPrivate::Space)) {
2214 setStatus(ReadPastEnd);
2215 return *this;
2216 }
2217
2218 QStringEncoder encoder(QStringConverter::Utf8);
2219 char *e = encoder.appendToBuffer(c, QStringView(ptr, length));
2220 *e = '\0';
2221 d->consumeLastToken();
2222 return *this;
2223}
2224
2225/*!
2226 \internal
2227 */
2228void QTextStreamPrivate::putNumber(qulonglong number, bool negative)
2229{
2230 unsigned flags = 0;
2231 const QTextStream::NumberFlags numberFlags = params.numberFlags;
2232 if (numberFlags & QTextStream::ShowBase)
2233 flags |= QLocaleData::ShowBase;
2234 // ForceSign is irrelevant when we'll be including a sign in any case:
2235 if ((numberFlags & QTextStream::ForceSign) && !negative)
2236 flags |= QLocaleData::AlwaysShowSign;
2237 if (numberFlags & QTextStream::UppercaseBase)
2238 flags |= QLocaleData::UppercaseBase;
2239 if (numberFlags & QTextStream::UppercaseDigits)
2240 flags |= QLocaleData::CapitalEorX;
2241
2242 // Group digits. For backward compatibility, we skip this for the C locale.
2243 if (locale != QLocale::c() && !locale.numberOptions().testFlag(QLocale::OmitGroupSeparator))
2244 flags |= QLocaleData::GroupDigits;
2245
2246 const QLocaleData *dd = locale.d->m_data;
2247 int base = params.integerBase ? params.integerBase : 10;
2248 QString result = dd->unsLongLongToString(number, -1, base, -1, flags);
2249 if (negative) {
2250 result.prepend(locale.negativeSign());
2251 } else if (number == 0 && base == 8 && params.numberFlags & QTextStream::ShowBase
2252 && result == "0"_L1) {
2253 // Workaround for backward compatibility - in octal form with ShowBase
2254 // flag set, zero should get its 0 prefix before its 0 value, but
2255 // QLocalePrivate only adds the prefix if the number doesn't start with
2256 // a zero.
2257 result.prepend(u'0');
2258 }
2259 putString(result, PutStringMode::Number);
2260}
2261
2262/*!
2263 Writes the character \a c to the stream, then returns a reference
2264 to the QTextStream.
2265
2266 \sa setFieldWidth()
2267*/
2268QTextStream &QTextStream::operator<<(QChar c)
2269{
2270 Q_D(QTextStream);
2271 CHECK_VALID_STREAM(*this);
2272 d->putChar(c);
2273 return *this;
2274}
2275
2276/*!
2277 \overload
2278
2279 Converts \a c from ASCII to a QChar, then writes it to the stream.
2280*/
2281QTextStream &QTextStream::operator<<(char c)
2282{
2283 Q_D(QTextStream);
2284 CHECK_VALID_STREAM(*this);
2285 d->putChar(QChar::fromLatin1(c));
2286 return *this;
2287}
2288
2289/*!
2290 \fn QTextStream &QTextStream::operator<<(char16_t c)
2291 \overload
2292 \since 6.3.1
2293
2294 Writes the Unicode character \a c to the stream, then returns a
2295 reference to the QTextStream.
2296*/
2297
2298/*!
2299 Writes the integer number \a i to the stream, then returns a
2300 reference to the QTextStream. By default, the number is stored in
2301 decimal form, but you can also set the base by calling
2302 setIntegerBase().
2303
2304 \sa setFieldWidth(), setNumberFlags()
2305*/
2306QTextStream &QTextStream::operator<<(signed short i)
2307{
2308 Q_D(QTextStream);
2309 CHECK_VALID_STREAM(*this);
2310 d->putNumber(QtPrivate::qUnsignedAbs(i), i < 0);
2311 return *this;
2312}
2313
2314/*!
2315 \overload
2316
2317 Writes the unsigned short \a i to the stream.
2318*/
2319QTextStream &QTextStream::operator<<(unsigned short i)
2320{
2321 Q_D(QTextStream);
2322 CHECK_VALID_STREAM(*this);
2323 d->putNumber((qulonglong)i, false);
2324 return *this;
2325}
2326
2327/*!
2328 \overload
2329
2330 Writes the signed int \a i to the stream.
2331*/
2332QTextStream &QTextStream::operator<<(signed int i)
2333{
2334 Q_D(QTextStream);
2335 CHECK_VALID_STREAM(*this);
2336 d->putNumber(QtPrivate::qUnsignedAbs(i), i < 0);
2337 return *this;
2338}
2339
2340/*!
2341 \overload
2342
2343 Writes the unsigned int \a i to the stream.
2344*/
2345QTextStream &QTextStream::operator<<(unsigned int i)
2346{
2347 Q_D(QTextStream);
2348 CHECK_VALID_STREAM(*this);
2349 d->putNumber((qulonglong)i, false);
2350 return *this;
2351}
2352
2353/*!
2354 \overload
2355
2356 Writes the signed long \a i to the stream.
2357*/
2358QTextStream &QTextStream::operator<<(signed long i)
2359{
2360 Q_D(QTextStream);
2361 CHECK_VALID_STREAM(*this);
2362 d->putNumber(QtPrivate::qUnsignedAbs(i), i < 0);
2363 return *this;
2364}
2365
2366/*!
2367 \overload
2368
2369 Writes the unsigned long \a i to the stream.
2370*/
2371QTextStream &QTextStream::operator<<(unsigned long i)
2372{
2373 Q_D(QTextStream);
2374 CHECK_VALID_STREAM(*this);
2375 d->putNumber((qulonglong)i, false);
2376 return *this;
2377}
2378
2379/*!
2380 \overload
2381
2382 Writes the qlonglong \a i to the stream.
2383*/
2384QTextStream &QTextStream::operator<<(qlonglong i)
2385{
2386 Q_D(QTextStream);
2387 CHECK_VALID_STREAM(*this);
2388 d->putNumber(QtPrivate::qUnsignedAbs(i), i < 0);
2389 return *this;
2390}
2391
2392/*!
2393 \overload
2394
2395 Writes the qulonglong \a i to the stream.
2396*/
2397QTextStream &QTextStream::operator<<(qulonglong i)
2398{
2399 Q_D(QTextStream);
2400 CHECK_VALID_STREAM(*this);
2401 d->putNumber(i, false);
2402 return *this;
2403}
2404
2405/*!
2406 Writes the real number \a f to the stream, then returns a
2407 reference to the QTextStream. By default, QTextStream stores it
2408 using SmartNotation, with up to 6 digits of precision. You can
2409 change the textual representation QTextStream will use for real
2410 numbers by calling setRealNumberNotation(),
2411 setRealNumberPrecision() and setNumberFlags().
2412
2413 \sa setFieldWidth(), setRealNumberNotation(),
2414 setRealNumberPrecision(), setNumberFlags()
2415*/
2416QTextStream &QTextStream::operator<<(float f)
2417{
2418 return *this << double(f);
2419}
2420
2421/*!
2422 \overload
2423
2424 Writes the double \a f to the stream.
2425*/
2426QTextStream &QTextStream::operator<<(double f)
2427{
2428 Q_D(QTextStream);
2429 CHECK_VALID_STREAM(*this);
2430
2431 QLocaleData::DoubleForm form = QLocaleData::DFDecimal;
2432 switch (realNumberNotation()) {
2433 case FixedNotation:
2434 form = QLocaleData::DFDecimal;
2435 break;
2436 case ScientificNotation:
2437 form = QLocaleData::DFExponent;
2438 break;
2439 case SmartNotation:
2440 form = QLocaleData::DFSignificantDigits;
2441 break;
2442 }
2443
2444 uint flags = 0;
2445 const QLocale::NumberOptions numberOptions = locale().numberOptions();
2446 if (numberFlags() & ShowBase)
2447 flags |= QLocaleData::ShowBase;
2448 if (numberFlags() & ForceSign)
2449 flags |= QLocaleData::AlwaysShowSign;
2450 if (numberFlags() & UppercaseBase)
2451 flags |= QLocaleData::UppercaseBase;
2452 if (numberFlags() & UppercaseDigits)
2453 flags |= QLocaleData::CapitalEorX;
2454 if (numberFlags() & ForcePoint) {
2455 flags |= QLocaleData::ForcePoint;
2456
2457 // Only for backwards compatibility
2458 flags |= QLocaleData::AddTrailingZeroes | QLocaleData::ShowBase;
2459 }
2460 if (locale() != QLocale::c() && !(numberOptions & QLocale::OmitGroupSeparator))
2461 flags |= QLocaleData::GroupDigits;
2462 if (!(numberOptions & QLocale::OmitLeadingZeroInExponent))
2463 flags |= QLocaleData::ZeroPadExponent;
2464 if (numberOptions & QLocale::IncludeTrailingZeroesAfterDot)
2465 flags |= QLocaleData::AddTrailingZeroes;
2466
2467 const QLocaleData *dd = d->locale.d->m_data;
2468 QString num = dd->doubleToString(f, d->params.realNumberPrecision, form, -1, flags);
2469 d->putString(num, QTextStreamPrivate::PutStringMode::Number);
2470 return *this;
2471}
2472
2473/*!
2474 Writes the string \a string to the stream, and returns a reference
2475 to the QTextStream. The string is first encoded using the assigned
2476 encoding (the default is UTF-8) before it is written to the stream.
2477
2478 \sa setFieldWidth(), setEncoding()
2479*/
2480QTextStream &QTextStream::operator<<(const QString &string)
2481{
2482 Q_D(QTextStream);
2483 CHECK_VALID_STREAM(*this);
2484 d->putString(string);
2485 return *this;
2486}
2487
2488/*!
2489 \overload
2490
2491 Writes \a string to the stream, and returns a reference to the
2492 QTextStream.
2493 \since 5.12
2494*/
2495QTextStream &QTextStream::operator<<(QStringView string)
2496{
2497 Q_D(QTextStream);
2498 CHECK_VALID_STREAM(*this);
2499 d->putString(string);
2500 return *this;
2501}
2502
2503/*!
2504 \overload
2505
2506 Writes \a string to the stream, and returns a reference to the
2507 QTextStream.
2508*/
2509QTextStream &QTextStream::operator<<(QLatin1StringView string)
2510{
2511 Q_D(QTextStream);
2512 CHECK_VALID_STREAM(*this);
2513 d->putString(string);
2514 return *this;
2515}
2516
2517/*!
2518 \overload
2519
2520 Writes \a array to the stream. The contents of \a array are
2521 converted with QString::fromUtf8().
2522*/
2523QTextStream &QTextStream::operator<<(const QByteArray &array)
2524{
2525 Q_D(QTextStream);
2526 CHECK_VALID_STREAM(*this);
2527 d->putString(QUtf8StringView{array});
2528 return *this;
2529}
2530
2531/*!
2532 \overload
2533
2534 Writes the constant string pointed to by \a string to the stream. \a
2535 string is assumed to be in UTF-8 encoding. This operator
2536 is convenient when working with constant string data. Example:
2537
2538 \snippet code/src_corelib_io_qtextstream.cpp 8
2539
2540 Warning: QTextStream assumes that \a string points to a string of
2541 text, terminated by a '\\0' character. If there is no terminating
2542 '\\0' character, your application may crash.
2543*/
2544QTextStream &QTextStream::operator<<(const char *string)
2545{
2546 Q_D(QTextStream);
2547 CHECK_VALID_STREAM(*this);
2548 d->putString(QUtf8StringView(string));
2549 return *this;
2550}
2551
2552/*!
2553 \overload
2554
2555 Writes \a ptr to the stream as a hexadecimal number with a base.
2556*/
2557
2558QTextStream &QTextStream::operator<<(const void *ptr)
2559{
2560 Q_D(QTextStream);
2561 CHECK_VALID_STREAM(*this);
2562 const int oldBase = d->params.integerBase;
2563 const NumberFlags oldFlags = d->params.numberFlags;
2564 d->params.integerBase = 16;
2565 d->params.numberFlags |= ShowBase;
2566 d->putNumber(reinterpret_cast<quintptr>(ptr), false);
2567 d->params.integerBase = oldBase;
2568 d->params.numberFlags = oldFlags;
2569 return *this;
2570}
2571
2572/*!
2573 \fn QTextStream::operator bool() const
2574 \since 6.10
2575
2576 Returns whether this stream has no errors (status() returns \l{Ok}).
2577*/
2578
2579namespace Qt {
2580
2581/*!
2582 Calls QTextStream::setIntegerBase(2) on \a stream and returns \a
2583 stream.
2584
2585 \since 5.14
2586
2587 \sa oct(), dec(), hex(), {QTextStream manipulators}
2588*/
2589QTextStream &bin(QTextStream &stream)
2590{
2592 return stream;
2593}
2594
2595/*!
2596 Calls QTextStream::setIntegerBase(8) on \a stream and returns \a
2597 stream.
2598
2599 \since 5.14
2600
2601 \sa bin(), dec(), hex(), {QTextStream manipulators}
2602*/
2603QTextStream &oct(QTextStream &stream)
2604{
2606 return stream;
2607}
2608
2609/*!
2610 Calls QTextStream::setIntegerBase(10) on \a stream and returns \a
2611 stream.
2612
2613 \since 5.14
2614
2615 \sa bin(), oct(), hex(), {QTextStream manipulators}
2616*/
2617QTextStream &dec(QTextStream &stream)
2618{
2620 return stream;
2621}
2622
2623/*!
2624 Calls QTextStream::setIntegerBase(16) on \a stream and returns \a
2625 stream.
2626
2627 \since 5.14
2628
2629 \note The hex modifier can only be used for writing to streams.
2630 \sa bin(), oct(), dec(), {QTextStream manipulators}
2631*/
2632QTextStream &hex(QTextStream &stream)
2633{
2635 return stream;
2636}
2637
2638/*!
2639 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2640 QTextStream::ShowBase) on \a stream and returns \a stream.
2641
2642 \since 5.14
2643
2644 \sa noshowbase(), forcesign(), forcepoint(), {QTextStream manipulators}
2645*/
2646QTextStream &showbase(QTextStream &stream)
2647{
2649 return stream;
2650}
2651
2652/*!
2653 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2654 QTextStream::ForceSign) on \a stream and returns \a stream.
2655
2656 \since 5.14
2657
2658 \sa noforcesign(), forcepoint(), showbase(), {QTextStream manipulators}
2659*/
2660QTextStream &forcesign(QTextStream &stream)
2661{
2663 return stream;
2664}
2665
2666/*!
2667 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2668 QTextStream::ForcePoint) on \a stream and returns \a stream.
2669
2670 \since 5.14
2671
2672 \sa noforcepoint(), forcesign(), showbase(), {QTextStream manipulators}
2673*/
2674QTextStream &forcepoint(QTextStream &stream)
2675{
2677 return stream;
2678}
2679
2680/*!
2681 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2682 ~QTextStream::ShowBase) on \a stream and returns \a stream.
2683
2684 \since 5.14
2685
2686 \sa showbase(), noforcesign(), noforcepoint(), {QTextStream manipulators}
2687*/
2688QTextStream &noshowbase(QTextStream &stream)
2689{
2691 return stream;
2692}
2693
2694/*!
2695 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2696 ~QTextStream::ForceSign) on \a stream and returns \a stream.
2697
2698 \since 5.14
2699
2700 \sa forcesign(), noforcepoint(), noshowbase(), {QTextStream manipulators}
2701*/
2702QTextStream &noforcesign(QTextStream &stream)
2703{
2705 return stream;
2706}
2707
2708/*!
2709 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2710 ~QTextStream::ForcePoint) on \a stream and returns \a stream.
2711
2712 \since 5.14
2713
2714 \sa forcepoint(), noforcesign(), noshowbase(), {QTextStream manipulators}
2715*/
2716QTextStream &noforcepoint(QTextStream &stream)
2717{
2719 return stream;
2720}
2721
2722/*!
2723 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2724 QTextStream::UppercaseBase) on \a stream and returns \a stream.
2725
2726 \since 5.14
2727
2728 \sa lowercasebase(), uppercasedigits(), {QTextStream manipulators}
2729*/
2730QTextStream &uppercasebase(QTextStream &stream)
2731{
2733 return stream;
2734}
2735
2736/*!
2737 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2738 QTextStream::UppercaseDigits) on \a stream and returns \a stream.
2739
2740 \since 5.14
2741
2742 \sa lowercasedigits(), uppercasebase(), {QTextStream manipulators}
2743*/
2744QTextStream &uppercasedigits(QTextStream &stream)
2745{
2747 return stream;
2748}
2749
2750/*!
2751 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2752 ~QTextStream::UppercaseBase) on \a stream and returns \a stream.
2753
2754 \since 5.14
2755
2756 \sa uppercasebase(), lowercasedigits(), {QTextStream manipulators}
2757*/
2758QTextStream &lowercasebase(QTextStream &stream)
2759{
2761 return stream;
2762}
2763
2764/*!
2765 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2766 ~QTextStream::UppercaseDigits) on \a stream and returns \a stream.
2767
2768 \since 5.14
2769
2770 \sa uppercasedigits(), lowercasebase(), {QTextStream manipulators}
2771*/
2772QTextStream &lowercasedigits(QTextStream &stream)
2773{
2775 return stream;
2776}
2777
2778/*!
2779 Calls QTextStream::setRealNumberNotation(QTextStream::FixedNotation)
2780 on \a stream and returns \a stream.
2781
2782 \since 5.14
2783
2784 \sa scientific(), {QTextStream manipulators}
2785*/
2786QTextStream &fixed(QTextStream &stream)
2787{
2789 return stream;
2790}
2791
2792/*!
2793 Calls QTextStream::setRealNumberNotation(QTextStream::ScientificNotation)
2794 on \a stream and returns \a stream.
2795
2796 \since 5.14
2797
2798 \sa fixed(), {QTextStream manipulators}
2799*/
2800QTextStream &scientific(QTextStream &stream)
2801{
2803 return stream;
2804}
2805
2806/*!
2807 Calls QTextStream::setFieldAlignment(QTextStream::AlignLeft)
2808 on \a stream and returns \a stream.
2809
2810 \since 5.14
2811
2812 \sa right(), center(), {QTextStream manipulators}
2813*/
2814QTextStream &left(QTextStream &stream)
2815{
2817 return stream;
2818}
2819
2820/*!
2821 Calls QTextStream::setFieldAlignment(QTextStream::AlignRight)
2822 on \a stream and returns \a stream.
2823
2824 \since 5.14
2825
2826 \sa left(), center(), {QTextStream manipulators}
2827*/
2828QTextStream &right(QTextStream &stream)
2829{
2831 return stream;
2832}
2833
2834/*!
2835 Calls QTextStream::setFieldAlignment(QTextStream::AlignCenter)
2836 on \a stream and returns \a stream.
2837
2838 \since 5.14
2839
2840 \sa left(), right(), {QTextStream manipulators}
2841*/
2842QTextStream &center(QTextStream &stream)
2843{
2845 return stream;
2846}
2847
2848/*!
2849 Writes '\\n' to the \a stream and flushes the stream.
2850
2851 Equivalent to
2852
2853 \snippet code/src_corelib_io_qtextstream.cpp 9
2854
2855 Note: On Windows, all '\\n' characters are written as '\\r\\n' if
2856 QTextStream's device or string is opened using the \l QIODeviceBase::Text flag.
2857
2858 \since 5.14
2859
2860 \sa flush(), reset(), {QTextStream manipulators}
2861*/
2862QTextStream &endl(QTextStream &stream)
2863{
2864 return stream << '\n'_L1 << Qt::flush;
2865}
2866
2867/*!
2868 Calls QTextStream::flush() on \a stream and returns \a stream.
2869
2870 \since 5.14
2871
2872 \sa endl(), reset(), {QTextStream manipulators}
2873*/
2874QTextStream &flush(QTextStream &stream)
2875{
2876 stream.flush();
2877 return stream;
2878}
2879
2880/*!
2881 Calls QTextStream::reset() on \a stream and returns \a stream.
2882
2883 \since 5.14
2884
2885 \sa flush(), {QTextStream manipulators}
2886*/
2887QTextStream &reset(QTextStream &stream)
2888{
2889 stream.reset();
2890 return stream;
2891}
2892
2893/*!
2894 Calls \l {QTextStream::}{skipWhiteSpace()} on \a stream and returns \a stream.
2895
2896 \since 5.14
2897
2898 \sa {QTextStream manipulators}
2899*/
2900QTextStream &ws(QTextStream &stream)
2901{
2903 return stream;
2904}
2905
2906} // namespace Qt
2907
2908/*!
2909 \fn QTextStreamManipulator qSetFieldWidth(int width)
2910 \relates QTextStream
2911
2912 Equivalent to QTextStream::setFieldWidth(\a width).
2913*/
2914
2915/*!
2916 \fn QTextStreamManipulator qSetPadChar(QChar ch)
2917 \relates QTextStream
2918
2919 Equivalent to QTextStream::setPadChar(\a ch).
2920*/
2921
2922/*!
2923 \fn QTextStreamManipulator qSetRealNumberPrecision(int precision)
2924 \relates QTextStream
2925
2926 Equivalent to QTextStream::setRealNumberPrecision(\a precision).
2927*/
2928
2929
2930namespace Qt {
2931/*!
2932 Toggles insertion of the Byte Order Mark on \a stream when QTextStream is
2933 used with a UTF encoding.
2934
2935 \since 5.14
2936
2937 \sa QTextStream::setGenerateByteOrderMark(), {QTextStream manipulators}
2938*/
2939QTextStream &bom(QTextStream &stream)
2940{
2942 return stream;
2943}
2944
2945} // namespace Qt
2946
2947
2948/*!
2949 \since 6.0
2950 Sets the encoding for this stream to \a encoding. The encoding is used for
2951 decoding any data that is read from the assigned device, and for
2952 encoding any data that is written. By default,
2953 QStringConverter::Utf8 is used, and automatic unicode
2954 detection is enabled.
2955
2956 If QTextStream operates on a string, this function does nothing.
2957
2958 \warning If you call this function while the text stream is reading
2959 from an open sequential socket, the internal buffer may still contain
2960 text decoded using the old encoding.
2961
2962 \sa encoding(), setAutoDetectUnicode(), setLocale()
2963*/
2964void QTextStream::setEncoding(QStringConverter::Encoding encoding)
2965{
2966 Q_D(QTextStream);
2967 if (d->encoding == encoding)
2968 return;
2969
2970 qint64 seekPos = -1;
2971 if (!d->readBuffer.isEmpty()) {
2972 if (!d->device->isSequential()) {
2973 seekPos = pos();
2974 }
2975 }
2976
2977 d->encoding = encoding;
2978 d->toUtf16 = QStringDecoder(d->encoding);
2979 bool generateBOM = !d->hasWrittenData && d->generateBOM;
2980 d->fromUtf16 = QStringEncoder(d->encoding,
2981 generateBOM ? QStringEncoder::Flag::WriteBom : QStringEncoder::Flag::Default);
2982
2983 if (seekPos >=0 && !d->readBuffer.isEmpty())
2984 seek(seekPos);
2985}
2986
2987/*!
2988 Returns the encoding that is current assigned to the stream.
2989
2990 \sa setEncoding(), setAutoDetectUnicode(), locale()
2991*/
2992QStringConverter::Encoding QTextStream::encoding() const
2993{
2994 Q_D(const QTextStream);
2995 return d->encoding;
2996}
2997
2998/*!
2999 If \a enabled is true, QTextStream will attempt to detect Unicode encoding
3000 by peeking into the stream data to see if it can find the UTF-8, UTF-16, or
3001 UTF-32 Byte Order Mark (BOM). If this mark is found, QTextStream will
3002 replace the current encoding with the UTF encoding.
3003
3004 This function can be used together with setEncoding(). It is common
3005 to set the encoding to UTF-8, and then enable UTF-16 detection.
3006
3007 \sa autoDetectUnicode(), setEncoding()
3008*/
3009void QTextStream::setAutoDetectUnicode(bool enabled)
3010{
3011 Q_D(QTextStream);
3012 d->autoDetectUnicode = enabled;
3013}
3014
3015/*!
3016 Returns \c true if automatic Unicode detection is enabled, otherwise
3017 returns \c false. Automatic Unicode detection is enabled by default.
3018
3019 \sa setAutoDetectUnicode(), setEncoding()
3020*/
3021bool QTextStream::autoDetectUnicode() const
3022{
3023 Q_D(const QTextStream);
3024 return d->autoDetectUnicode;
3025}
3026
3027/*!
3028 If \a generate is true and a UTF encoding is used, QTextStream will insert
3029 the BOM (Byte Order Mark) before any data has been written to the
3030 device. If \a generate is false, no BOM will be inserted. This function
3031 must be called before any data is written. Otherwise, it does nothing.
3032
3033 \sa generateByteOrderMark(), {Qt::}{bom()}
3034*/
3035void QTextStream::setGenerateByteOrderMark(bool generate)
3036{
3037 Q_D(QTextStream);
3038 if (d->hasWrittenData || d->generateBOM == generate)
3039 return;
3040
3041 d->generateBOM = generate;
3042 d->fromUtf16 = QStringEncoder(d->encoding, generate ? QStringConverter::Flag::WriteBom : QStringConverter::Flag::Default);
3043}
3044
3045/*!
3046 Returns \c true if QTextStream is set to generate the UTF BOM (Byte Order
3047 Mark) when using a UTF encoding; otherwise returns \c false. UTF BOM generation is
3048 set to false by default.
3049
3050 \sa setGenerateByteOrderMark()
3051*/
3052bool QTextStream::generateByteOrderMark() const
3053{
3054 Q_D(const QTextStream);
3055 return d->generateBOM;
3056}
3057
3058/*!
3059 \since 4.5
3060
3061 Sets the locale for this stream to \a locale. The specified locale is
3062 used for conversions between numbers and their string representations.
3063
3064 The default locale is C and it is a special case - the thousands
3065 group separator is not used for backward compatibility reasons.
3066
3067 \sa locale()
3068*/
3069void QTextStream::setLocale(const QLocale &locale)
3070{
3071 Q_D(QTextStream);
3072 d->locale = locale;
3073}
3074
3075/*!
3076 \since 4.5
3077
3078 Returns the locale for this stream. The default locale is C.
3079
3080 \sa setLocale()
3081*/
3082QLocale QTextStream::locale() const
3083{
3084 Q_D(const QTextStream);
3085 return d->locale;
3086}
3087
3088QT_END_NAMESPACE
Definition qcompare.h:76
#define Q_VOID
Definition qiodevice.cpp:46
static const qsizetype QTEXTSTREAM_BUFFERSIZE
#define IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(type)
#define IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(type)
#define CHECK_VALID_STREAM(x)