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