1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtCore module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 //#define QTEXTSTREAM_DEBUG
43 static const int QTEXTSTREAM_BUFFERSIZE = 16384;
48 \brief The QTextStream class provides a convenient interface for
49 reading and writing text.
52 \ingroup string-processing
55 QTextStream can operate on a QIODevice, a QByteArray or a
56 QString. Using QTextStream's streaming operators, you can
57 conveniently read and write words, lines and numbers. For
58 generating text, QTextStream supports formatting options for field
59 padding and alignment, and formatting of numbers. Example:
61 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 0
63 It's also common to use QTextStream to read console input and write
64 console output. QTextStream is locale aware, and will automatically decode
65 standard input using the correct codec. Example:
67 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 1
69 Besides using QTextStream's constructors, you can also set the
70 device or string QTextStream operates on by calling setDevice() or
71 setString(). You can seek to a position by calling seek(), and
72 atEnd() will return true when there is no data left to be read. If
73 you call flush(), QTextStream will empty all data from its write
74 buffer into the device and call flush() on the device.
76 Internally, QTextStream uses a Unicode based buffer, and
77 QTextCodec is used by QTextStream to automatically support
78 different character sets. By default, QTextCodec::codecForLocale()
79 is used for reading and writing, but you can also set the codec by
80 calling setCodec(). Automatic Unicode detection is also
81 supported. When this feature is enabled (the default behavior),
82 QTextStream will detect the UTF-16 or the UTF-32 BOM (Byte Order Mark) and
83 switch to the appropriate UTF codec when reading. QTextStream
84 does not write a BOM by default, but you can enable this by calling
85 setGenerateByteOrderMark(true). When QTextStream operates on a QString
86 directly, the codec is disabled.
88 There are three general ways to use QTextStream when reading text
93 \o Chunk by chunk, by calling readLine() or readAll().
95 \o Word by word. QTextStream supports streaming into QStrings,
96 QByteArrays and char* buffers. Words are delimited by space, and
97 leading white space is automatically skipped.
99 \o Character by character, by streaming into QChar or char types.
100 This method is often used for convenient input handling when
101 parsing files, independent of character encoding and end-of-line
102 semantics. To skip white space, call skipWhiteSpace().
106 Since the text stream uses a buffer, you should not read from
107 the stream using the implementation of a superclass. For instance,
108 if you have a QFile and read from it directly using
109 QFile::readLine() instead of using the stream, the text stream's
110 internal position will be out of sync with the file's position.
112 By default, when reading numbers from a stream of text,
113 QTextStream will automatically detect the number's base
114 representation. For example, if the number starts with "0x", it is
115 assumed to be in hexadecimal form. If it starts with the digits
116 1-9, it is assumed to be in decimal form, and so on. You can set
117 the integer base, thereby disabling the automatic detection, by
118 calling setIntegerBase(). Example:
120 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 2
122 QTextStream supports many formatting options for generating text.
123 You can set the field width and pad character by calling
124 setFieldWidth() and setPadChar(). Use setFieldAlignment() to set
125 the alignment within each field. For real numbers, call
126 setRealNumberNotation() and setRealNumberPrecision() to set the
127 notation (SmartNotation, ScientificNotation, FixedNotation) and precision in
128 digits of the generated number. Some extra number formatting
129 options are also available through setNumberFlags().
131 \keyword QTextStream manipulators
133 Like \c <iostream> in the standard C++ library, QTextStream also
134 defines several global manipulator functions:
137 \header \o Manipulator \o Description
138 \row \o \c bin \o Same as setIntegerBase(2).
139 \row \o \c oct \o Same as setIntegerBase(8).
140 \row \o \c dec \o Same as setIntegerBase(10).
141 \row \o \c hex \o Same as setIntegerBase(16).
142 \row \o \c showbase \o Same as setNumberFlags(numberFlags() | ShowBase).
143 \row \o \c forcesign \o Same as setNumberFlags(numberFlags() | ForceSign).
144 \row \o \c forcepoint \o Same as setNumberFlags(numberFlags() | ForcePoint).
145 \row \o \c noshowbase \o Same as setNumberFlags(numberFlags() & ~ShowBase).
146 \row \o \c noforcesign \o Same as setNumberFlags(numberFlags() & ~ForceSign).
147 \row \o \c noforcepoint \o Same as setNumberFlags(numberFlags() & ~ForcePoint).
148 \row \o \c uppercasebase \o Same as setNumberFlags(numberFlags() | UppercaseBase).
149 \row \o \c uppercasedigits \o Same as setNumberFlags(numberFlags() | UppercaseDigits).
150 \row \o \c lowercasebase \o Same as setNumberFlags(numberFlags() & ~UppercaseBase).
151 \row \o \c lowercasedigits \o Same as setNumberFlags(numberFlags() & ~UppercaseDigits).
152 \row \o \c fixed \o Same as setRealNumberNotation(FixedNotation).
153 \row \o \c scientific \o Same as setRealNumberNotation(ScientificNotation).
154 \row \o \c left \o Same as setFieldAlignment(AlignLeft).
155 \row \o \c right \o Same as setFieldAlignment(AlignRight).
156 \row \o \c center \o Same as setFieldAlignment(AlignCenter).
157 \row \o \c endl \o Same as operator<<('\n') and flush().
158 \row \o \c flush \o Same as flush().
159 \row \o \c reset \o Same as reset().
160 \row \o \c ws \o Same as skipWhiteSpace().
161 \row \o \c bom \o Same as setGenerateByteOrderMark(true).
164 In addition, Qt provides three global manipulators that take a
165 parameter: qSetFieldWidth(), qSetPadChar(), and
166 qSetRealNumberPrecision().
168 \sa QDataStream, QIODevice, QFile, QBuffer, QTcpSocket, {Codecs Example}
171 /*! \enum QTextStream::RealNumberNotation
173 This enum specifies which notations to use for expressing \c
174 float and \c double as strings.
176 \value ScientificNotation Scientific notation (\c{printf()}'s \c %e flag).
177 \value FixedNotation Fixed-point notation (\c{printf()}'s \c %f flag).
178 \value SmartNotation Scientific or fixed-point notation, depending on which makes most sense (\c{printf()}'s \c %g flag).
180 \sa setRealNumberNotation()
183 /*! \enum QTextStream::FieldAlignment
185 This enum specifies how to align text in fields when the field is
186 wider than the text that occupies it.
188 \value AlignLeft Pad on the right side of fields.
189 \value AlignRight Pad on the left side of fields.
190 \value AlignCenter Pad on both sides of field.
191 \value AlignAccountingStyle Same as AlignRight, except that the
192 sign of a number is flush left.
194 \sa setFieldAlignment()
197 /*! \enum QTextStream::NumberFlag
199 This enum specifies various flags that can be set to affect the
200 output of integers, \c{float}s, and \c{double}s.
202 \value ShowBase Show the base as a prefix if the base
203 is 16 ("0x"), 8 ("0"), or 2 ("0b").
204 \value ForcePoint Always put the decimal separator in numbers, even if
205 there are no decimals.
206 \value ForceSign Always put the sign in numbers, even for positive numbers.
207 \value UppercaseBase Use uppercase versions of base prefixes ("0X", "0B").
208 \value UppercaseDigits Use uppercase letters for expressing
209 digits 10 to 35 instead of lowercase.
214 /*! \enum QTextStream::Status
216 This enum describes the current status of the text stream.
218 \value Ok The text stream is operating normally.
219 \value ReadPastEnd The text stream has read past the end of the
220 data in the underlying device.
221 \value ReadCorruptData The text stream has read corrupt data.
222 \value WriteFailed The text stream cannot write to the underlying device.
227 #include "qtextstream.h"
230 #include "qnumeric.h"
231 #ifndef QT_NO_TEXTCODEC
232 #include "qtextcodec.h"
237 #include "private/qlocale_p.h"
243 #if defined QTEXTSTREAM_DEBUG
248 // Returns a human readable representation of the first \a len
249 // characters in \a data.
250 static QByteArray qt_prettyDebug(const char *data, int len, int maxSize)
252 if (!data) return "(null)";
254 for (int i = 0; i < len; ++i) {
256 if (isprint(int(uchar(c)))) {
259 case '\n': out += "\\n"; break;
260 case '\r': out += "\\r"; break;
261 case '\t': out += "\\t"; break;
264 tmp.sprintf("\\x%x", (unsigned int)(unsigned char)c);
265 out += tmp.toLatin1();
278 // A precondition macro
280 #define CHECK_VALID_STREAM(x) do { \
281 if (!d->string && !d->device) { \
282 qWarning("QTextStream: No device"); \
286 // Base implementations of operator>> for ints and reals
287 #define IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(type) do { \
289 CHECK_VALID_STREAM(*this); \
291 switch (d->getNumber(&tmp)) { \
292 case QTextStreamPrivate::npsOk: \
295 case QTextStreamPrivate::npsMissingDigit: \
296 case QTextStreamPrivate::npsInvalidPrefix: \
298 setStatus(atEnd() ? QTextStream::ReadPastEnd : QTextStream::ReadCorruptData); \
301 return *this; } while (0)
303 #define IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(type) do { \
305 CHECK_VALID_STREAM(*this); \
307 if (d->getReal(&tmp)) { \
311 setStatus(atEnd() ? QTextStream::ReadPastEnd : QTextStream::ReadCorruptData); \
313 return *this; } while (0)
317 #ifndef QT_NO_QOBJECT
318 class QDeviceClosedNotifier : public QObject
322 inline QDeviceClosedNotifier()
325 inline void setupDevice(QTextStream *stream, QIODevice *device)
329 connect(device, SIGNAL(aboutToClose()), this, SLOT(flushStream()));
330 this->stream = stream;
334 inline void flushStream() { stream->flush(); }
341 //-------------------------------------------------------------------
342 class QTextStreamPrivate
344 Q_DECLARE_PUBLIC(QTextStream)
346 QTextStreamPrivate(QTextStream *q_ptr);
347 ~QTextStreamPrivate();
352 #ifndef QT_NO_QOBJECT
353 QDeviceClosedNotifier deviceClosedNotifier;
360 QIODevice::OpenMode stringOpenMode;
362 #ifndef QT_NO_TEXTCODEC
365 QTextCodec::ConverterState readConverterState;
366 QTextCodec::ConverterState writeConverterState;
367 QTextCodec::ConverterState *readConverterSavedState;
368 bool autoDetectUnicode;
372 enum TokenDelimiter {
378 QString read(int maxlen);
379 bool scan(const QChar **ptr, int *tokenLength,
380 int maxlen, TokenDelimiter delimiter);
381 inline const QChar *readPtr() const;
382 inline void consumeLastToken();
383 inline void consume(int nchars);
384 void saveConverterState(qint64 newPos);
385 void restoreToSavedConverterState();
388 // Return value type for getNumber()
389 enum NumberParsingStatus {
395 inline bool getChar(QChar *ch);
396 inline void ungetChar(const QChar &ch);
397 NumberParsingStatus getNumber(qulonglong *l);
398 bool getReal(double *f);
400 inline void write(const QString &data);
401 inline void putString(const QString &ch, bool number = false);
402 void putNumber(qulonglong number, bool negative);
405 bool fillReadBuffer(qint64 maxBytes = -1);
406 void resetReadBuffer();
407 void flushWriteBuffer();
410 int readBufferOffset;
411 int readConverterSavedStateOffset; //the offset between readBufferStartDevicePos and that start of the buffer
412 qint64 readBufferStartDevicePos;
414 // streaming parameters
415 int realNumberPrecision;
419 QTextStream::FieldAlignment fieldAlignment;
420 QTextStream::RealNumberNotation realNumberNotation;
421 QTextStream::NumberFlags numberFlags;
424 QTextStream::Status status;
433 QTextStreamPrivate::QTextStreamPrivate(QTextStream *q_ptr)
435 #ifndef QT_NO_TEXTCODEC
436 readConverterSavedState(0),
438 readConverterSavedStateOffset(0),
447 QTextStreamPrivate::~QTextStreamPrivate()
450 #ifndef QT_NO_QOBJECT
451 device->blockSignals(true);
455 #ifndef QT_NO_TEXTCODEC
456 delete readConverterSavedState;
460 #ifndef QT_NO_TEXTCODEC
461 static void resetCodecConverterStateHelper(QTextCodec::ConverterState *state)
463 state->~ConverterState();
464 new (state) QTextCodec::ConverterState;
467 static void copyConverterStateHelper(QTextCodec::ConverterState *dest,
468 const QTextCodec::ConverterState *src)
470 // ### QTextCodec::ConverterState's copy constructors and assignments are
471 // private. This function copies the structure manually.
473 dest->flags = src->flags;
474 dest->invalidChars = src->invalidChars;
475 dest->state_data[0] = src->state_data[0];
476 dest->state_data[1] = src->state_data[1];
477 dest->state_data[2] = src->state_data[2];
483 void QTextStreamPrivate::reset()
485 realNumberPrecision = 6;
488 padChar = QLatin1Char(' ');
489 fieldAlignment = QTextStream::AlignRight;
490 realNumberNotation = QTextStream::SmartNotation;
494 deleteDevice = false;
497 stringOpenMode = QIODevice::NotOpen;
499 readBufferOffset = 0;
500 readBufferStartDevicePos = 0;
503 #ifndef QT_NO_TEXTCODEC
504 codec = QTextCodec::codecForLocale();
505 resetCodecConverterStateHelper(&readConverterState);
506 resetCodecConverterStateHelper(&writeConverterState);
507 delete readConverterSavedState;
508 readConverterSavedState = 0;
509 writeConverterState.flags |= QTextCodec::IgnoreHeader;
510 autoDetectUnicode = true;
516 bool QTextStreamPrivate::fillReadBuffer(qint64 maxBytes)
518 // no buffer next to the QString itself; this function should only
519 // be called internally, for devices.
523 // handle text translation and bypass the Text flag in the device.
524 bool textModeEnabled = device->isTextModeEnabled();
526 device->setTextModeEnabled(false);
528 // read raw data into a temporary buffer
529 char buf[QTEXTSTREAM_BUFFERSIZE];
530 qint64 bytesRead = 0;
531 #if defined(Q_OS_WIN)
532 // On Windows, there is no non-blocking stdin - so we fall back to reading
533 // lines instead. If there is no QOBJECT, we read lines for all sequential
534 // devices; otherwise, we read lines only for stdin.
537 if (device->isSequential()
538 #if !defined(QT_NO_QOBJECT)
539 && (file = qobject_cast<QFile *>(device)) && file->handle() == 0
543 bytesRead = device->readLine(buf, qMin<qint64>(sizeof(buf), maxBytes));
545 bytesRead = device->readLine(buf, sizeof(buf));
550 bytesRead = device->read(buf, qMin<qint64>(sizeof(buf), maxBytes));
552 bytesRead = device->read(buf, sizeof(buf));
555 #ifndef QT_NO_TEXTCODEC
556 // codec auto detection, explicitly defaults to locale encoding if the
557 // codec has been set to 0.
558 if (!codec || autoDetectUnicode) {
559 autoDetectUnicode = false;
561 codec = QTextCodec::codecForUtfText(QByteArray::fromRawData(buf, bytesRead), codec);
563 codec = QTextCodec::codecForLocale();
564 writeConverterState.flags |= QTextCodec::IgnoreHeader;
567 #if defined (QTEXTSTREAM_DEBUG)
568 qDebug("QTextStreamPrivate::fillReadBuffer(), using %s codec",
569 codec->name().constData());
573 #if defined (QTEXTSTREAM_DEBUG)
574 qDebug("QTextStreamPrivate::fillReadBuffer(), device->read(\"%s\", %d) == %d",
575 qt_prettyDebug(buf, qMin(32,int(bytesRead)) , int(bytesRead)).constData(), sizeof(buf), int(bytesRead));
581 int oldReadBufferSize = readBuffer.size();
582 #ifndef QT_NO_TEXTCODEC
583 // convert to unicode
584 readBuffer += codec->toUnicode(buf, bytesRead, &readConverterState);
586 readBuffer += QString::fromLatin1(QByteArray(buf, bytesRead).constData());
589 // reset the Text flag.
591 device->setTextModeEnabled(true);
593 // remove all '\r\n' in the string.
594 if (readBuffer.size() > oldReadBufferSize && textModeEnabled) {
595 QChar CR = QLatin1Char('\r');
596 QChar *writePtr = readBuffer.data() + oldReadBufferSize;
597 QChar *readPtr = readBuffer.data() + oldReadBufferSize;
598 QChar *endPtr = readBuffer.data() + readBuffer.size();
600 int n = oldReadBufferSize;
601 if (readPtr < endPtr) {
602 // Cut-off to avoid unnecessary self-copying.
603 while (*readPtr++ != CR) {
605 if (++writePtr == endPtr)
609 while (readPtr < endPtr) {
610 QChar ch = *readPtr++;
614 if (n < readBufferOffset)
620 readBuffer.resize(writePtr - readBuffer.data());
623 #if defined (QTEXTSTREAM_DEBUG)
624 qDebug("QTextStreamPrivate::fillReadBuffer() read %d bytes from device. readBuffer = [%s]", int(bytesRead),
625 qt_prettyDebug(readBuffer.toLatin1(), readBuffer.size(), readBuffer.size()).data());
632 void QTextStreamPrivate::resetReadBuffer()
635 readBufferOffset = 0;
636 readBufferStartDevicePos = (device ? device->pos() : 0);
641 void QTextStreamPrivate::flushWriteBuffer()
643 // no buffer next to the QString itself; this function should only
644 // be called internally, for devices.
645 if (string || !device)
648 // Stream went bye-bye already. Appending further data may succeed again,
649 // but would create a corrupted stream anyway.
650 if (status != QTextStream::Ok)
653 if (writeBuffer.isEmpty())
656 #if defined (Q_OS_WIN)
657 // handle text translation and bypass the Text flag in the device.
658 bool textModeEnabled = device->isTextModeEnabled();
659 if (textModeEnabled) {
660 device->setTextModeEnabled(false);
661 writeBuffer.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
665 #ifndef QT_NO_TEXTCODEC
667 codec = QTextCodec::codecForLocale();
668 #if defined (QTEXTSTREAM_DEBUG)
669 qDebug("QTextStreamPrivate::flushWriteBuffer(), using %s codec (%s generating BOM)",
670 codec->name().constData(), writeConverterState.flags & QTextCodec::IgnoreHeader ? "not" : "");
673 // convert from unicode to raw data
674 QByteArray data = codec->fromUnicode(writeBuffer.data(), writeBuffer.size(), &writeConverterState);
676 QByteArray data = writeBuffer.toLocal8Bit();
680 // write raw data to the device
681 qint64 bytesWritten = device->write(data);
682 #if defined (QTEXTSTREAM_DEBUG)
683 qDebug("QTextStreamPrivate::flushWriteBuffer(), device->write(\"%s\") == %d",
684 qt_prettyDebug(data.constData(), qMin(data.size(),32), data.size()).constData(), int(bytesWritten));
686 if (bytesWritten <= 0) {
687 status = QTextStream::WriteFailed;
691 #if defined (Q_OS_WIN)
692 // replace the text flag
694 device->setTextModeEnabled(true);
698 #ifndef QT_NO_QOBJECT
699 QFile *file = qobject_cast<QFile *>(device);
700 bool flushed = !file || file->flush();
705 #if defined (QTEXTSTREAM_DEBUG)
706 qDebug("QTextStreamPrivate::flushWriteBuffer() wrote %d bytes",
709 if (!flushed || bytesWritten != qint64(data.size()))
710 status = QTextStream::WriteFailed;
713 QString QTextStreamPrivate::read(int maxlen)
717 lastTokenSize = qMin(maxlen, string->size() - stringOffset);
718 ret = string->mid(stringOffset, lastTokenSize);
720 while (readBuffer.size() - readBufferOffset < maxlen && fillReadBuffer()) ;
721 lastTokenSize = qMin(maxlen, readBuffer.size() - readBufferOffset);
722 ret = readBuffer.mid(readBufferOffset, lastTokenSize);
726 #if defined (QTEXTSTREAM_DEBUG)
727 qDebug("QTextStreamPrivate::read() maxlen = %d, token length = %d", maxlen, ret.length());
734 Scans no more than \a maxlen QChars in the current buffer for the
735 first \a delimiter. Stores a pointer to the start offset of the
736 token in \a ptr, and the length in QChars in \a length.
738 bool QTextStreamPrivate::scan(const QChar **ptr, int *length, int maxlen, TokenDelimiter delimiter)
742 bool consumeDelimiter = false;
743 bool foundToken = false;
744 int startOffset = device ? readBufferOffset : stringOffset;
747 bool canStillReadFromDevice = true;
752 chPtr = readBuffer.constData();
753 endOffset = readBuffer.size();
755 chPtr = string->constData();
756 endOffset = string->size();
758 chPtr += startOffset;
760 for (; !foundToken && startOffset < endOffset && (!maxlen || totalSize < maxlen); ++startOffset) {
761 const QChar ch = *chPtr++;
778 if (ch == QLatin1Char('\n')) {
780 delimSize = (lastChar == QLatin1Char('\r')) ? 2 : 1;
781 consumeDelimiter = true;
788 && (!maxlen || totalSize < maxlen)
789 && (device && (canStillReadFromDevice = fillReadBuffer())));
791 // if the token was not found, but we reached the end of input,
792 // then we accept what we got. if we are not at the end of input,
794 if (!foundToken && (!maxlen || totalSize < maxlen)
796 || (string && stringOffset + totalSize < string->size())
797 || (device && !device->atEnd() && canStillReadFromDevice))) {
798 #if defined (QTEXTSTREAM_DEBUG)
799 qDebug("QTextStreamPrivate::scan() did not find the token.");
804 // if we find a '\r' at the end of the data when reading lines,
805 // don't make it part of the line.
806 if (delimiter == EndOfLine && totalSize > 0 && !foundToken) {
807 if (((string && stringOffset + totalSize == string->size()) || (device && device->atEnd()))
808 && lastChar == QLatin1Char('\r')) {
809 consumeDelimiter = true;
814 // set the read offset and length of the token
816 *length = totalSize - delimSize;
820 // update last token size. the callee will call consumeLastToken() when
822 lastTokenSize = totalSize;
823 if (!consumeDelimiter)
824 lastTokenSize -= delimSize;
826 #if defined (QTEXTSTREAM_DEBUG)
827 qDebug("QTextStreamPrivate::scan(%p, %p, %d, %x) token length = %d, delimiter = %d",
828 ptr, length, maxlen, (int)delimiter, totalSize - delimSize, delimSize);
835 inline const QChar *QTextStreamPrivate::readPtr() const
837 Q_ASSERT(readBufferOffset <= readBuffer.size());
839 return string->constData() + stringOffset;
840 return readBuffer.constData() + readBufferOffset;
845 inline void QTextStreamPrivate::consumeLastToken()
848 consume(lastTokenSize);
854 inline void QTextStreamPrivate::consume(int size)
856 #if defined (QTEXTSTREAM_DEBUG)
857 qDebug("QTextStreamPrivate::consume(%d)", size);
860 stringOffset += size;
861 if (stringOffset > string->size())
862 stringOffset = string->size();
864 readBufferOffset += size;
865 if (readBufferOffset >= readBuffer.size()) {
866 readBufferOffset = 0;
868 saveConverterState(device->pos());
869 } else if (readBufferOffset > QTEXTSTREAM_BUFFERSIZE) {
870 readBuffer = readBuffer.remove(0,readBufferOffset);
871 readConverterSavedStateOffset += readBufferOffset;
872 readBufferOffset = 0;
879 inline void QTextStreamPrivate::saveConverterState(qint64 newPos)
881 #ifndef QT_NO_TEXTCODEC
882 if (readConverterState.d) {
883 // converter cannot be copied, so don't save anything
884 // don't update readBufferStartDevicePos either
888 if (!readConverterSavedState)
889 readConverterSavedState = new QTextCodec::ConverterState;
890 copyConverterStateHelper(readConverterSavedState, &readConverterState);
893 readBufferStartDevicePos = newPos;
894 readConverterSavedStateOffset = 0;
899 inline void QTextStreamPrivate::restoreToSavedConverterState()
901 #ifndef QT_NO_TEXTCODEC
902 if (readConverterSavedState) {
903 // we have a saved state
904 // that means the converter can be copied
905 copyConverterStateHelper(&readConverterState, readConverterSavedState);
907 // the only state we could save was the initial
909 resetCodecConverterStateHelper(&readConverterState);
916 inline void QTextStreamPrivate::write(const QString &data)
919 // ### What about seek()??
920 string->append(data);
923 if (writeBuffer.size() > QTEXTSTREAM_BUFFERSIZE)
930 inline bool QTextStreamPrivate::getChar(QChar *ch)
932 if ((string && stringOffset == string->size())
933 || (device && readBuffer.isEmpty() && !fillReadBuffer())) {
946 inline void QTextStreamPrivate::ungetChar(const QChar &ch)
949 if (stringOffset == 0)
952 (*string)[--stringOffset] = ch;
956 if (readBufferOffset == 0) {
957 readBuffer.prepend(ch);
961 readBuffer[--readBufferOffset] = ch;
966 inline void QTextStreamPrivate::putString(const QString &s, bool number)
971 int padSize = fieldWidth - s.size();
973 QString pad(padSize, padChar);
974 if (fieldAlignment == QTextStream::AlignLeft) {
975 tmp.append(QString(padSize, padChar));
976 } else if (fieldAlignment == QTextStream::AlignRight
977 || fieldAlignment == QTextStream::AlignAccountingStyle) {
978 tmp.prepend(QString(padSize, padChar));
979 if (fieldAlignment == QTextStream::AlignAccountingStyle && number) {
980 const QChar sign = s.size() > 0 ? s.at(0) : QChar();
981 if (sign == locale.negativeSign() || sign == locale.positiveSign()) {
982 QChar *data = tmp.data();
983 data[padSize] = tmp.at(0);
987 } else if (fieldAlignment == QTextStream::AlignCenter) {
988 tmp.prepend(QString(padSize/2, padChar));
989 tmp.append(QString(padSize - padSize/2, padChar));
993 #if defined (QTEXTSTREAM_DEBUG)
994 QByteArray a = s.toUtf8();
995 QByteArray b = tmp.toUtf8();
996 qDebug("QTextStreamPrivate::putString(\"%s\") calls write(\"%s\")",
997 qt_prettyDebug(a.constData(), a.size(), qMax(16, a.size())).constData(),
998 qt_prettyDebug(b.constData(), b.size(), qMax(16, b.size())).constData());
1004 Constructs a QTextStream. Before you can use it for reading or
1005 writing, you must assign a device or a string.
1007 \sa setDevice(), setString()
1009 QTextStream::QTextStream()
1010 : d_ptr(new QTextStreamPrivate(this))
1012 #if defined (QTEXTSTREAM_DEBUG)
1013 qDebug("QTextStream::QTextStream()");
1020 Constructs a QTextStream that operates on \a device.
1022 QTextStream::QTextStream(QIODevice *device)
1023 : d_ptr(new QTextStreamPrivate(this))
1025 #if defined (QTEXTSTREAM_DEBUG)
1026 qDebug("QTextStream::QTextStream(QIODevice *device == *%p)",
1031 #ifndef QT_NO_QOBJECT
1032 d->deviceClosedNotifier.setupDevice(this, d->device);
1038 Constructs a QTextStream that operates on \a string, using \a
1039 openMode to define the open mode.
1041 QTextStream::QTextStream(QString *string, QIODevice::OpenMode openMode)
1042 : d_ptr(new QTextStreamPrivate(this))
1044 #if defined (QTEXTSTREAM_DEBUG)
1045 qDebug("QTextStream::QTextStream(QString *string == *%p, openMode = %d)",
1046 string, int(openMode));
1050 d->stringOpenMode = openMode;
1055 Constructs a QTextStream that operates on \a array, using \a
1056 openMode to define the open mode. Internally, the array is wrapped
1059 QTextStream::QTextStream(QByteArray *array, QIODevice::OpenMode openMode)
1060 : d_ptr(new QTextStreamPrivate(this))
1062 #if defined (QTEXTSTREAM_DEBUG)
1063 qDebug("QTextStream::QTextStream(QByteArray *array == *%p, openMode = %d)",
1064 array, int(openMode));
1067 d->device = new QBuffer(array);
1068 d->device->open(openMode);
1069 d->deleteDevice = true;
1070 #ifndef QT_NO_QOBJECT
1071 d->deviceClosedNotifier.setupDevice(this, d->device);
1077 Constructs a QTextStream that operates on \a array, using \a
1078 openMode to define the open mode. The array is accessed as
1079 read-only, regardless of the values in \a openMode.
1081 This constructor is convenient for working on constant
1084 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 3
1086 QTextStream::QTextStream(const QByteArray &array, QIODevice::OpenMode openMode)
1087 : d_ptr(new QTextStreamPrivate(this))
1089 #if defined (QTEXTSTREAM_DEBUG)
1090 qDebug("QTextStream::QTextStream(const QByteArray &array == *(%p), openMode = %d)",
1091 &array, int(openMode));
1093 QBuffer *buffer = new QBuffer;
1094 buffer->setData(array);
1095 buffer->open(openMode);
1099 d->deleteDevice = true;
1100 #ifndef QT_NO_QOBJECT
1101 d->deviceClosedNotifier.setupDevice(this, d->device);
1107 Constructs a QTextStream that operates on \a fileHandle, using \a
1108 openMode to define the open mode. Internally, a QFile is created
1109 to handle the FILE pointer.
1111 This constructor is useful for working directly with the common
1112 FILE based input and output streams: stdin, stdout and stderr. Example:
1114 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 4
1117 QTextStream::QTextStream(FILE *fileHandle, QIODevice::OpenMode openMode)
1118 : d_ptr(new QTextStreamPrivate(this))
1120 #if defined (QTEXTSTREAM_DEBUG)
1121 qDebug("QTextStream::QTextStream(FILE *fileHandle = %p, openMode = %d)",
1122 fileHandle, int(openMode));
1124 QFile *file = new QFile;
1125 file->open(fileHandle, openMode);
1129 d->deleteDevice = true;
1130 #ifndef QT_NO_QOBJECT
1131 d->deviceClosedNotifier.setupDevice(this, d->device);
1137 Destroys the QTextStream.
1139 If the stream operates on a device, flush() will be called
1140 implicitly. Otherwise, the device is unaffected.
1142 QTextStream::~QTextStream()
1145 #if defined (QTEXTSTREAM_DEBUG)
1146 qDebug("QTextStream::~QTextStream()");
1148 if (!d->writeBuffer.isEmpty())
1149 d->flushWriteBuffer();
1153 Resets QTextStream's formatting options, bringing it back to its
1154 original constructed state. The device, string and any buffered
1155 data is left untouched.
1157 void QTextStream::reset()
1161 d->realNumberPrecision = 6;
1164 d->padChar = QLatin1Char(' ');
1165 d->fieldAlignment = QTextStream::AlignRight;
1166 d->realNumberNotation = QTextStream::SmartNotation;
1171 Flushes any buffered data waiting to be written to the device.
1173 If QTextStream operates on a string, this function does nothing.
1175 void QTextStream::flush()
1178 d->flushWriteBuffer();
1182 Seeks to the position \a pos in the device. Returns true on
1183 success; otherwise returns false.
1185 bool QTextStream::seek(qint64 pos)
1188 d->lastTokenSize = 0;
1191 // Empty the write buffer
1192 d->flushWriteBuffer();
1193 if (!d->device->seek(pos))
1195 d->resetReadBuffer();
1197 #ifndef QT_NO_TEXTCODEC
1198 // Reset the codec converter states.
1199 resetCodecConverterStateHelper(&d->readConverterState);
1200 resetCodecConverterStateHelper(&d->writeConverterState);
1201 delete d->readConverterSavedState;
1202 d->readConverterSavedState = 0;
1203 d->writeConverterState.flags |= QTextCodec::IgnoreHeader;
1209 if (d->string && pos <= d->string->size()) {
1210 d->stringOffset = int(pos);
1219 Returns the device position corresponding to the current position of the
1220 stream, or -1 if an error occurs (e.g., if there is no device or string,
1221 or if there's a device error).
1223 Because QTextStream is buffered, this function may have to
1224 seek the device to reconstruct a valid device position. This
1225 operation can be expensive, so you may want to avoid calling this
1226 function in a tight loop.
1230 qint64 QTextStream::pos() const
1232 Q_D(const QTextStream);
1235 if (d->readBuffer.isEmpty())
1236 return d->device->pos();
1237 if (d->device->isSequential())
1241 if (!d->device->seek(d->readBufferStartDevicePos))
1244 // Reset the read buffer
1245 QTextStreamPrivate *thatd = const_cast<QTextStreamPrivate *>(d);
1246 thatd->readBuffer.clear();
1248 #ifndef QT_NO_TEXTCODEC
1249 thatd->restoreToSavedConverterState();
1250 if (d->readBufferStartDevicePos == 0)
1251 thatd->autoDetectUnicode = true;
1254 // Rewind the device to get to the current position Ensure that
1255 // readBufferOffset is unaffected by fillReadBuffer()
1256 int oldReadBufferOffset = d->readBufferOffset + d->readConverterSavedStateOffset;
1257 while (d->readBuffer.size() < oldReadBufferOffset) {
1258 if (!thatd->fillReadBuffer(1))
1261 thatd->readBufferOffset = oldReadBufferOffset;
1262 thatd->readConverterSavedStateOffset = 0;
1264 // Return the device position.
1265 return d->device->pos();
1269 return d->stringOffset;
1271 qWarning("QTextStream::pos: no device");
1276 Reads and discards whitespace from the stream until either a
1277 non-space character is detected, or until atEnd() returns
1278 true. This function is useful when reading a stream character by
1281 Whitespace characters are all characters for which
1282 QChar::isSpace() returns true.
1286 void QTextStream::skipWhiteSpace()
1289 CHECK_VALID_STREAM(Q_VOID);
1290 d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
1291 d->consumeLastToken();
1295 Sets the current device to \a device. If a device has already been
1296 assigned, QTextStream will call flush() before the old device is
1299 \note This function resets locale to the default locale ('C')
1300 and codec to the default codec, QTextCodec::codecForLocale().
1302 \sa device(), setString()
1304 void QTextStream::setDevice(QIODevice *device)
1308 if (d->deleteDevice) {
1309 #ifndef QT_NO_QOBJECT
1310 d->deviceClosedNotifier.disconnect();
1313 d->deleteDevice = false;
1319 d->resetReadBuffer();
1320 #ifndef QT_NO_QOBJECT
1321 d->deviceClosedNotifier.setupDevice(this, d->device);
1326 Returns the current device associated with the QTextStream,
1327 or 0 if no device has been assigned.
1329 \sa setDevice(), string()
1331 QIODevice *QTextStream::device() const
1333 Q_D(const QTextStream);
1338 Sets the current string to \a string, using the given \a
1339 openMode. If a device has already been assigned, QTextStream will
1340 call flush() before replacing it.
1342 \sa string(), setDevice()
1344 void QTextStream::setString(QString *string, QIODevice::OpenMode openMode)
1348 if (d->deleteDevice) {
1349 #ifndef QT_NO_QOBJECT
1350 d->deviceClosedNotifier.disconnect();
1351 d->device->blockSignals(true);
1354 d->deleteDevice = false;
1360 d->stringOpenMode = openMode;
1364 Returns the current string assigned to the QTextStream, or 0 if no
1365 string has been assigned.
1367 \sa setString(), device()
1369 QString *QTextStream::string() const
1371 Q_D(const QTextStream);
1376 Sets the field alignment to \a mode. When used together with
1377 setFieldWidth(), this function allows you to generate formatted
1378 output with text aligned to the left, to the right or center
1381 \sa fieldAlignment(), setFieldWidth()
1383 void QTextStream::setFieldAlignment(FieldAlignment mode)
1386 d->fieldAlignment = mode;
1390 Returns the current field alignment.
1392 \sa setFieldAlignment(), fieldWidth()
1394 QTextStream::FieldAlignment QTextStream::fieldAlignment() const
1396 Q_D(const QTextStream);
1397 return d->fieldAlignment;
1401 Sets the pad character to \a ch. The default value is the ASCII
1402 space character (' '), or QChar(0x20). This character is used to
1403 fill in the space in fields when generating text.
1407 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 5
1409 The string \c s contains:
1411 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 6
1413 \sa padChar(), setFieldWidth()
1415 void QTextStream::setPadChar(QChar ch)
1422 Returns the current pad character.
1424 \sa setPadChar(), setFieldWidth()
1426 QChar QTextStream::padChar() const
1428 Q_D(const QTextStream);
1433 Sets the current field width to \a width. If \a width is 0 (the
1434 default), the field width is equal to the length of the generated
1437 \note The field width applies to every element appended to this
1438 stream after this function has been called (e.g., it also pads
1439 endl). This behavior is different from similar classes in the STL,
1440 where the field width only applies to the next element.
1442 \sa fieldWidth(), setPadChar()
1444 void QTextStream::setFieldWidth(int width)
1447 d->fieldWidth = width;
1451 Returns the current field width.
1455 int QTextStream::fieldWidth() const
1457 Q_D(const QTextStream);
1458 return d->fieldWidth;
1462 Sets the current number flags to \a flags. \a flags is a set of
1463 flags from the NumberFlag enum, and describes options for
1464 formatting generated code (e.g., whether or not to always write
1465 the base or sign of a number).
1467 \sa numberFlags(), setIntegerBase(), setRealNumberNotation()
1469 void QTextStream::setNumberFlags(NumberFlags flags)
1472 d->numberFlags = flags;
1476 Returns the current number flags.
1478 \sa setNumberFlags(), integerBase(), realNumberNotation()
1480 QTextStream::NumberFlags QTextStream::numberFlags() const
1482 Q_D(const QTextStream);
1483 return d->numberFlags;
1487 Sets the base of integers to \a base, both for reading and for
1488 generating numbers. \a base can be either 2 (binary), 8 (octal),
1489 10 (decimal) or 16 (hexadecimal). If \a base is 0, QTextStream
1490 will attempt to detect the base by inspecting the data on the
1491 stream. When generating numbers, QTextStream assumes base is 10
1492 unless the base has been set explicitly.
1494 \sa integerBase(), QString::number(), setNumberFlags()
1496 void QTextStream::setIntegerBase(int base)
1499 d->integerBase = base;
1503 Returns the current base of integers. 0 means that the base is
1504 detected when reading, or 10 (decimal) when generating numbers.
1506 \sa setIntegerBase(), QString::number(), numberFlags()
1508 int QTextStream::integerBase() const
1510 Q_D(const QTextStream);
1511 return d->integerBase;
1515 Sets the real number notation to \a notation (SmartNotation,
1516 FixedNotation, ScientificNotation). When reading and generating
1517 numbers, QTextStream uses this value to detect the formatting of
1520 \sa realNumberNotation(), setRealNumberPrecision(), setNumberFlags(), setIntegerBase()
1522 void QTextStream::setRealNumberNotation(RealNumberNotation notation)
1525 d->realNumberNotation = notation;
1529 Returns the current real number notation.
1531 \sa setRealNumberNotation(), realNumberPrecision(), numberFlags(), integerBase()
1533 QTextStream::RealNumberNotation QTextStream::realNumberNotation() const
1535 Q_D(const QTextStream);
1536 return d->realNumberNotation;
1540 Sets the precision of real numbers to \a precision. This value
1541 describes the number of fraction digits QTextStream should
1542 write when generating real numbers.
1544 The precision cannot be a negative value. The default value is 6.
1546 \sa realNumberPrecision(), setRealNumberNotation()
1548 void QTextStream::setRealNumberPrecision(int precision)
1551 if (precision < 0) {
1552 qWarning("QTextStream::setRealNumberPrecision: Invalid precision (%d)", precision);
1553 d->realNumberPrecision = 6;
1556 d->realNumberPrecision = precision;
1560 Returns the current real number precision, or the number of fraction
1561 digits QTextStream will write when generating real numbers.
1563 \sa setRealNumberNotation(), realNumberNotation(), numberFlags(), integerBase()
1565 int QTextStream::realNumberPrecision() const
1567 Q_D(const QTextStream);
1568 return d->realNumberPrecision;
1572 Returns the status of the text stream.
1574 \sa QTextStream::Status, setStatus(), resetStatus()
1577 QTextStream::Status QTextStream::status() const
1579 Q_D(const QTextStream);
1586 Resets the status of the text stream.
1588 \sa QTextStream::Status, status(), setStatus()
1590 void QTextStream::resetStatus()
1599 Sets the status of the text stream to the \a status given.
1601 Subsequent calls to setStatus() are ignored until resetStatus()
1604 \sa Status status() resetStatus()
1606 void QTextStream::setStatus(Status status)
1609 if (d->status == Ok)
1614 Returns true if there is no more data to be read from the
1615 QTextStream; otherwise returns false. This is similar to, but not
1616 the same as calling QIODevice::atEnd(), as QTextStream also takes
1617 into account its internal Unicode buffer.
1619 bool QTextStream::atEnd() const
1621 Q_D(const QTextStream);
1622 CHECK_VALID_STREAM(true);
1625 return d->string->size() == d->stringOffset;
1626 return d->readBuffer.isEmpty() && d->device->atEnd();
1630 Reads the entire content of the stream, and returns it as a
1631 QString. Avoid this function when working on large files, as it
1632 will consume a significant amount of memory.
1634 Calling readLine() is better if you do not know how much data is
1639 QString QTextStream::readAll()
1642 CHECK_VALID_STREAM(QString());
1644 return d->read(INT_MAX);
1648 Reads one line of text from the stream, and returns it as a
1649 QString. The maximum allowed line length is set to \a maxlen. If
1650 the stream contains lines longer than this, then the lines will be
1651 split after \a maxlen characters and returned in parts.
1653 If \a maxlen is 0, the lines can be of any length. A common value
1654 for \a maxlen is 75.
1656 The returned line has no trailing end-of-line characters ("\\n"
1657 or "\\r\\n"), so calling QString::trimmed() is unnecessary.
1659 If the stream has read to the end of the file, readLine() will return a
1660 null QString. For strings, or for devices that support it, you can
1661 explicitly test for the end of the stream using atEnd().
1663 \sa readAll(), QIODevice::readLine()
1665 QString QTextStream::readLine(qint64 maxlen)
1668 CHECK_VALID_STREAM(QString());
1670 const QChar *readPtr;
1672 if (!d->scan(&readPtr, &length, int(maxlen), QTextStreamPrivate::EndOfLine))
1675 QString tmp = QString(readPtr, length);
1676 d->consumeLastToken();
1683 Reads at most \a maxlen characters from the stream, and returns the data
1686 \sa readAll(), readLine(), QIODevice::read()
1688 QString QTextStream::read(qint64 maxlen)
1691 CHECK_VALID_STREAM(QString());
1694 return QString::fromLatin1(""); // empty, not null
1696 return d->read(int(maxlen));
1701 QTextStreamPrivate::NumberParsingStatus QTextStreamPrivate::getNumber(qulonglong *ret)
1703 scan(0, 0, 0, NotSpace);
1706 // detect int encoding
1707 int base = integerBase;
1711 return npsInvalidPrefix;
1712 if (ch == QLatin1Char('0')) {
1714 if (!getChar(&ch2)) {
1715 // Result is the number 0
1719 ch2 = ch2.toLower();
1721 if (ch2 == QLatin1Char('x')) {
1723 } else if (ch2 == QLatin1Char('b')) {
1725 } else if (ch2.isDigit() && ch2.digitValue() >= 0 && ch2.digitValue() <= 7) {
1731 } else if (ch == locale.negativeSign() || ch == locale.positiveSign() || ch.isDigit()) {
1735 return npsInvalidPrefix;
1738 // State of the stream is now the same as on entry
1739 // (cursor is at prefix),
1740 // and local variable 'base' has been set appropriately.
1746 QChar pf1, pf2, dig;
1747 // Parse prefix '0b'
1748 if (!getChar(&pf1) || pf1 != QLatin1Char('0'))
1749 return npsInvalidPrefix;
1750 if (!getChar(&pf2) || pf2.toLower() != QLatin1Char('b'))
1751 return npsInvalidPrefix;
1754 while (getChar(&dig)) {
1755 int n = dig.toLower().unicode();
1756 if (n == '0' || n == '1') {
1766 // Unwind the prefix and abort
1769 return npsMissingDigit;
1776 if (!getChar(&pf) || pf != QLatin1Char('0'))
1777 return npsInvalidPrefix;
1780 while (getChar(&dig)) {
1781 int n = dig.toLower().unicode();
1782 if (n >= '0' && n <= '7') {
1792 // Unwind the prefix and abort
1794 return npsMissingDigit;
1799 // Parse sign (or first digit)
1802 if (!getChar(&sign))
1803 return npsMissingDigit;
1804 if (sign != locale.negativeSign() && sign != locale.positiveSign()) {
1805 if (!sign.isDigit()) {
1807 return npsMissingDigit;
1809 val += sign.digitValue();
1814 while (getChar(&ch)) {
1817 val += ch.digitValue();
1818 } else if (locale != QLocale::c() && ch == locale.groupSeparator()) {
1827 return npsMissingDigit;
1828 if (sign == locale.negativeSign()) {
1829 qlonglong ival = qlonglong(val);
1832 val = qulonglong(ival);
1837 QChar pf1, pf2, dig;
1838 // Parse prefix ' 0x'
1839 if (!getChar(&pf1) || pf1 != QLatin1Char('0'))
1840 return npsInvalidPrefix;
1841 if (!getChar(&pf2) || pf2.toLower() != QLatin1Char('x'))
1842 return npsInvalidPrefix;
1845 while (getChar(&dig)) {
1846 int n = dig.toLower().unicode();
1847 if (n >= '0' && n <= '9') {
1850 } else if (n >= 'a' && n <= 'f') {
1852 val += 10 + (n - 'a');
1860 return npsMissingDigit;
1865 // Unsupported integerBase
1866 return npsInvalidPrefix;
1877 bool QTextStreamPrivate::getReal(double *f)
1879 // We use a table-driven FSM to parse floating point numbers
1880 // strtod() cannot be used directly since we may be reading from a
1911 static const uchar table[13][10] = {
1912 // None InputSign InputDigit InputDot InputExp InputI InputN InputF InputA InputT
1913 { 0, Sign, Mantissa, Dot, 0, Inf1, Nan1, 0, 0, 0 }, // 0 Init
1914 { 0, 0, Mantissa, Dot, 0, Inf1, Nan1, 0, 0, 0 }, // 1 Sign
1915 { Done, Done, Mantissa, Dot, ExpMark, 0, 0, 0, 0, 0 }, // 2 Mantissa
1916 { 0, 0, Abscissa, 0, 0, 0, 0, 0, 0, 0 }, // 3 Dot
1917 { Done, Done, Abscissa, Done, ExpMark, 0, 0, 0, 0, 0 }, // 4 Abscissa
1918 { 0, ExpSign, Exponent, 0, 0, 0, 0, 0, 0, 0 }, // 5 ExpMark
1919 { 0, 0, Exponent, 0, 0, 0, 0, 0, 0, 0 }, // 6 ExpSign
1920 { Done, Done, Exponent, Done, Done, 0, 0, 0, 0, 0 }, // 7 Exponent
1921 { 0, 0, 0, 0, 0, 0, 0, 0, Nan2, 0 }, // 8 Nan1
1922 { 0, 0, 0, 0, 0, 0, NanInf, 0, 0, 0 }, // 9 Nan2
1923 { 0, 0, 0, 0, 0, 0, Inf2, 0, 0, 0 }, // 10 Inf1
1924 { 0, 0, 0, 0, 0, 0, 0, NanInf, 0, 0 }, // 11 Inf2
1925 { Done, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // 11 NanInf
1928 ParserState state = Init;
1929 InputToken input = None;
1931 scan(0, 0, 0, NotSpace);
1934 const int BufferSize = 128;
1935 char buf[BufferSize];
1939 while (getChar(&c)) {
1940 switch (c.unicode()) {
1941 case '0': case '1': case '2': case '3': case '4':
1942 case '5': case '6': case '7': case '8': case '9':
1961 QChar lc = c.toLower();
1962 if (lc == locale.decimalPoint().toLower())
1964 else if (lc == locale.exponential().toLower())
1966 else if (lc == locale.negativeSign().toLower()
1967 || lc == locale.positiveSign().toLower())
1969 else if (locale != QLocale::c() // backward-compatibility
1970 && lc == locale.groupSeparator().toLower())
1971 input = InputDigit; // well, it isn't a digit, but no one cares.
1978 state = ParserState(table[state][input]);
1980 if (state == Init || state == Done || i > (BufferSize - 5)) {
1982 if (i > (BufferSize - 5)) { // ignore rest of digits
1983 while (getChar(&c)) {
1993 buf[i++] = c.toLatin1();
2002 // backward-compatibility. Old implementation supported +nan/-nan
2003 // for some reason. QLocale only checks for lower-case
2004 // nan/+inf/-inf, so here we also check for uppercase and mixed
2006 if (!qstricmp(buf, "nan") || !qstricmp(buf, "+nan") || !qstricmp(buf, "-nan")) {
2009 } else if (!qstricmp(buf, "+inf") || !qstricmp(buf, "inf")) {
2012 } else if (!qstricmp(buf, "-inf")) {
2017 *f = locale.toDouble(QString::fromLatin1(buf), &ok);
2022 Reads a character from the stream and stores it in \a c. Returns a
2023 reference to the QTextStream, so several operators can be
2026 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 7
2028 Whitespace is \e not skipped.
2031 QTextStream &QTextStream::operator>>(QChar &c)
2034 CHECK_VALID_STREAM(*this);
2035 d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
2036 if (!d->getChar(&c))
2037 setStatus(ReadPastEnd);
2044 Reads a character from the stream and stores it in \a c. The
2045 character from the stream is converted to ISO-5589-1 before it is
2048 \sa QChar::toLatin1()
2050 QTextStream &QTextStream::operator>>(char &c)
2059 Reads an integer from the stream and stores it in \a i, then
2060 returns a reference to the QTextStream. The number is cast to
2061 the correct type before it is stored. If no number was detected on
2062 the stream, \a i is set to 0.
2064 By default, QTextStream will attempt to detect the base of the
2065 number using the following rules:
2068 \header \o Prefix \o Base
2069 \row \o "0b" or "0B" \o 2 (binary)
2070 \row \o "0" followed by "0-7" \o 8 (octal)
2071 \row \o "0" otherwise \o 10 (decimal)
2072 \row \o "0x" or "0X" \o 16 (hexadecimal)
2073 \row \o "1" to "9" \o 10 (decimal)
2076 By calling setIntegerBase(), you can specify the integer base
2077 explicitly. This will disable the auto-detection, and speed up
2078 QTextStream slightly.
2080 Leading whitespace is skipped.
2082 QTextStream &QTextStream::operator>>(signed short &i)
2084 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(signed short);
2090 Stores the integer in the unsigned short \a i.
2092 QTextStream &QTextStream::operator>>(unsigned short &i)
2094 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(unsigned short);
2100 Stores the integer in the signed int \a i.
2102 QTextStream &QTextStream::operator>>(signed int &i)
2104 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(signed int);
2110 Stores the integer in the unsigned int \a i.
2112 QTextStream &QTextStream::operator>>(unsigned int &i)
2114 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(unsigned int);
2120 Stores the integer in the signed long \a i.
2122 QTextStream &QTextStream::operator>>(signed long &i)
2124 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(signed long);
2130 Stores the integer in the unsigned long \a i.
2132 QTextStream &QTextStream::operator>>(unsigned long &i)
2134 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(unsigned long);
2140 Stores the integer in the qlonglong \a i.
2142 QTextStream &QTextStream::operator>>(qlonglong &i)
2144 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(qlonglong);
2150 Stores the integer in the qulonglong \a i.
2152 QTextStream &QTextStream::operator>>(qulonglong &i)
2154 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(qulonglong);
2158 Reads a real number from the stream and stores it in \a f, then
2159 returns a reference to the QTextStream. The number is cast to
2160 the correct type. If no real number is detect on the stream, \a f
2163 As a special exception, QTextStream allows the strings "nan" and "inf" to
2164 represent NAN and INF floats or doubles.
2166 Leading whitespace is skipped.
2168 QTextStream &QTextStream::operator>>(float &f)
2170 IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(float);
2176 Stores the real number in the double \a f.
2178 QTextStream &QTextStream::operator>>(double &f)
2180 IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(double);
2184 Reads a word from the stream and stores it in \a str, then returns
2185 a reference to the stream. Words are separated by whitespace
2186 (i.e., all characters for which QChar::isSpace() returns true).
2188 Leading whitespace is skipped.
2190 QTextStream &QTextStream::operator>>(QString &str)
2193 CHECK_VALID_STREAM(*this);
2196 d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
2197 d->consumeLastToken();
2201 if (!d->scan(&ptr, &length, 0, QTextStreamPrivate::Space)) {
2202 setStatus(ReadPastEnd);
2206 str = QString(ptr, length);
2207 d->consumeLastToken();
2214 Converts the word to ISO-8859-1, then stores it in \a array.
2216 \sa QString::toLatin1()
2218 QTextStream &QTextStream::operator>>(QByteArray &array)
2221 CHECK_VALID_STREAM(*this);
2224 d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
2225 d->consumeLastToken();
2229 if (!d->scan(&ptr, &length, 0, QTextStreamPrivate::Space)) {
2230 setStatus(ReadPastEnd);
2234 for (int i = 0; i < length; ++i)
2235 array += ptr[i].toLatin1();
2237 d->consumeLastToken();
2244 Stores the word in \a c, terminated by a '\0' character. If no word is
2245 available, only the '\0' character is stored.
2247 Warning: Although convenient, this operator is dangerous and must
2248 be used with care. QTextStream assumes that \a c points to a
2249 buffer with enough space to hold the word. If the buffer is too
2250 small, your application may crash.
2252 If possible, use the QByteArray operator instead.
2254 QTextStream &QTextStream::operator>>(char *c)
2258 CHECK_VALID_STREAM(*this);
2259 d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
2260 d->consumeLastToken();
2264 if (!d->scan(&ptr, &length, 0, QTextStreamPrivate::Space)) {
2265 setStatus(ReadPastEnd);
2269 for (int i = 0; i < length; ++i)
2270 *c++ = ptr[i].toLatin1();
2272 d->consumeLastToken();
2278 void QTextStreamPrivate::putNumber(qulonglong number, bool negative)
2283 if (numberFlags & QTextStream::ShowBase)
2284 flags |= QLocalePrivate::ShowBase;
2285 if (numberFlags & QTextStream::ForceSign)
2286 flags |= QLocalePrivate::AlwaysShowSign;
2287 if (numberFlags & QTextStream::UppercaseBase)
2288 flags |= QLocalePrivate::UppercaseBase;
2289 if (numberFlags & QTextStream::UppercaseDigits)
2290 flags |= QLocalePrivate::CapitalEorX;
2292 // add thousands group separators. For backward compatibility we
2293 // don't add a group separator for C locale.
2294 if (locale != QLocale::c())
2295 flags |= QLocalePrivate::ThousandsGroup;
2297 const QLocalePrivate *dd = locale.d();
2298 int base = integerBase ? integerBase : 10;
2299 if (negative && base == 10) {
2300 result = dd->longLongToString(-static_cast<qlonglong>(number), -1,
2302 } else if (negative) {
2303 // Workaround for backward compatibility for writing negative
2304 // numbers in octal and hex:
2305 // QTextStream(result) << showbase << hex << -1 << oct << -1
2306 // should output: -0x1 -0b1
2307 result = dd->unsLongLongToString(number, -1, base, -1, flags);
2308 result.prepend(locale.negativeSign());
2310 result = dd->unsLongLongToString(number, -1, base, -1, flags);
2311 // workaround for backward compatibility - in octal form with
2312 // ShowBase flag set zero should be written as '00'
2313 if (number == 0 && base == 8 && numberFlags & QTextStream::ShowBase
2314 && result == QLatin1String("0")) {
2315 result.prepend(QLatin1Char('0'));
2318 putString(result, true);
2322 Writes the character \a c to the stream, then returns a reference
2327 QTextStream &QTextStream::operator<<(QChar c)
2330 CHECK_VALID_STREAM(*this);
2331 d->putString(QString(c));
2338 Converts \a c from ASCII to a QChar, then writes it to the stream.
2340 QTextStream &QTextStream::operator<<(char c)
2343 CHECK_VALID_STREAM(*this);
2344 d->putString(QString(QChar::fromAscii(c)));
2349 Writes the integer number \a i to the stream, then returns a
2350 reference to the QTextStream. By default, the number is stored in
2351 decimal form, but you can also set the base by calling
2354 \sa setFieldWidth(), setNumberFlags()
2356 QTextStream &QTextStream::operator<<(signed short i)
2359 CHECK_VALID_STREAM(*this);
2360 d->putNumber((qulonglong)qAbs(qlonglong(i)), i < 0);
2367 Writes the unsigned short \a i to the stream.
2369 QTextStream &QTextStream::operator<<(unsigned short i)
2372 CHECK_VALID_STREAM(*this);
2373 d->putNumber((qulonglong)i, false);
2380 Writes the signed int \a i to the stream.
2382 QTextStream &QTextStream::operator<<(signed int i)
2385 CHECK_VALID_STREAM(*this);
2386 d->putNumber((qulonglong)qAbs(qlonglong(i)), i < 0);
2393 Writes the unsigned int \a i to the stream.
2395 QTextStream &QTextStream::operator<<(unsigned int i)
2398 CHECK_VALID_STREAM(*this);
2399 d->putNumber((qulonglong)i, false);
2406 Writes the signed long \a i to the stream.
2408 QTextStream &QTextStream::operator<<(signed long i)
2411 CHECK_VALID_STREAM(*this);
2412 d->putNumber((qulonglong)qAbs(qlonglong(i)), i < 0);
2419 Writes the unsigned long \a i to the stream.
2421 QTextStream &QTextStream::operator<<(unsigned long i)
2424 CHECK_VALID_STREAM(*this);
2425 d->putNumber((qulonglong)i, false);
2432 Writes the qlonglong \a i to the stream.
2434 QTextStream &QTextStream::operator<<(qlonglong i)
2437 CHECK_VALID_STREAM(*this);
2438 d->putNumber((qulonglong)qAbs(i), i < 0);
2445 Writes the qulonglong \a i to the stream.
2447 QTextStream &QTextStream::operator<<(qulonglong i)
2450 CHECK_VALID_STREAM(*this);
2451 d->putNumber(i, false);
2456 Writes the real number \a f to the stream, then returns a
2457 reference to the QTextStream. By default, QTextStream stores it
2458 using SmartNotation, with up to 6 digits of precision. You can
2459 change the textual representation QTextStream will use for real
2460 numbers by calling setRealNumberNotation(),
2461 setRealNumberPrecision() and setNumberFlags().
2463 \sa setFieldWidth(), setRealNumberNotation(),
2464 setRealNumberPrecision(), setNumberFlags()
2466 QTextStream &QTextStream::operator<<(float f)
2468 return *this << double(f);
2474 Writes the double \a f to the stream.
2476 QTextStream &QTextStream::operator<<(double f)
2479 CHECK_VALID_STREAM(*this);
2481 QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
2482 switch (realNumberNotation()) {
2484 form = QLocalePrivate::DFDecimal;
2486 case ScientificNotation:
2487 form = QLocalePrivate::DFExponent;
2490 form = QLocalePrivate::DFSignificantDigits;
2495 if (numberFlags() & ShowBase)
2496 flags |= QLocalePrivate::ShowBase;
2497 if (numberFlags() & ForceSign)
2498 flags |= QLocalePrivate::AlwaysShowSign;
2499 if (numberFlags() & UppercaseBase)
2500 flags |= QLocalePrivate::UppercaseBase;
2501 if (numberFlags() & UppercaseDigits)
2502 flags |= QLocalePrivate::CapitalEorX;
2503 if (numberFlags() & ForcePoint)
2504 flags |= QLocalePrivate::Alternate;
2506 const QLocalePrivate *dd = d->locale.d();
2507 QString num = dd->doubleToString(f, d->realNumberPrecision, form, -1, flags);
2508 d->putString(num, true);
2513 Writes the string \a string to the stream, and returns a reference
2514 to the QTextStream. The string is first encoded using the assigned
2515 codec (the default codec is QTextCodec::codecForLocale()) before
2516 it is written to the stream.
2518 \sa setFieldWidth(), setCodec()
2520 QTextStream &QTextStream::operator<<(const QString &string)
2523 CHECK_VALID_STREAM(*this);
2524 d->putString(string);
2531 Writes \a string to the stream, and returns a reference to the
2532 QTextStream. The contents of \a string are converted with the
2533 QString constructor that takes a QLatin1String as argument.
2535 QTextStream &QTextStream::operator<<(const QLatin1String &string)
2538 CHECK_VALID_STREAM(*this);
2539 d->putString(QString(string));
2546 Writes \a array to the stream. The contents of \a array are
2547 converted with QString::fromAscii().
2549 QTextStream &QTextStream::operator<<(const QByteArray &array)
2552 CHECK_VALID_STREAM(*this);
2553 d->putString(QString::fromAscii(array.constData(), array.length()));
2560 Writes the constant string pointed to by \a string to the stream. \a
2561 string is assumed to be in ISO-8859-1 encoding. This operator
2562 is convenient when working with constant string data. Example:
2564 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 8
2566 Warning: QTextStream assumes that \a string points to a string of
2567 text, terminated by a '\0' character. If there is no terminating
2568 '\0' character, your application may crash.
2570 QTextStream &QTextStream::operator<<(const char *string)
2573 CHECK_VALID_STREAM(*this);
2574 d->putString(QLatin1String(string));
2581 Writes \a ptr to the stream as a hexadecimal number with a base.
2584 QTextStream &QTextStream::operator<<(const void *ptr)
2587 CHECK_VALID_STREAM(*this);
2588 int oldBase = d->integerBase;
2589 NumberFlags oldFlags = d->numberFlags;
2590 d->integerBase = 16;
2591 d->numberFlags |= ShowBase;
2592 d->putNumber(reinterpret_cast<quintptr>(ptr), false);
2593 d->integerBase = oldBase;
2594 d->numberFlags = oldFlags;
2599 \relates QTextStream
2601 Calls QTextStream::setIntegerBase(2) on \a stream and returns \a
2604 \sa oct(), dec(), hex(), {QTextStream manipulators}
2606 QTextStream &bin(QTextStream &stream)
2608 stream.setIntegerBase(2);
2613 \relates QTextStream
2615 Calls QTextStream::setIntegerBase(8) on \a stream and returns \a
2618 \sa bin(), dec(), hex(), {QTextStream manipulators}
2620 QTextStream &oct(QTextStream &stream)
2622 stream.setIntegerBase(8);
2627 \relates QTextStream
2629 Calls QTextStream::setIntegerBase(10) on \a stream and returns \a
2632 \sa bin(), oct(), hex(), {QTextStream manipulators}
2634 QTextStream &dec(QTextStream &stream)
2636 stream.setIntegerBase(10);
2641 \relates QTextStream
2643 Calls QTextStream::setIntegerBase(16) on \a stream and returns \a
2646 \note The hex modifier can only be used for writing to streams.
2647 \sa bin(), oct(), dec(), {QTextStream manipulators}
2649 QTextStream &hex(QTextStream &stream)
2651 stream.setIntegerBase(16);
2656 \relates QTextStream
2658 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2659 QTextStream::ShowBase) on \a stream and returns \a stream.
2661 \sa noshowbase(), forcesign(), forcepoint(), {QTextStream manipulators}
2663 QTextStream &showbase(QTextStream &stream)
2665 stream.setNumberFlags(stream.numberFlags() | QTextStream::ShowBase);
2670 \relates QTextStream
2672 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2673 QTextStream::ForceSign) on \a stream and returns \a stream.
2675 \sa noforcesign(), forcepoint(), showbase(), {QTextStream manipulators}
2677 QTextStream &forcesign(QTextStream &stream)
2679 stream.setNumberFlags(stream.numberFlags() | QTextStream::ForceSign);
2684 \relates QTextStream
2686 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2687 QTextStream::ForcePoint) on \a stream and returns \a stream.
2689 \sa noforcepoint(), forcesign(), showbase(), {QTextStream manipulators}
2691 QTextStream &forcepoint(QTextStream &stream)
2693 stream.setNumberFlags(stream.numberFlags() | QTextStream::ForcePoint);
2698 \relates QTextStream
2700 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2701 ~QTextStream::ShowBase) on \a stream and returns \a stream.
2703 \sa showbase(), noforcesign(), noforcepoint(), {QTextStream manipulators}
2705 QTextStream &noshowbase(QTextStream &stream)
2707 stream.setNumberFlags(stream.numberFlags() &= ~QTextStream::ShowBase);
2712 \relates QTextStream
2714 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2715 ~QTextStream::ForceSign) on \a stream and returns \a stream.
2717 \sa forcesign(), noforcepoint(), noshowbase(), {QTextStream manipulators}
2719 QTextStream &noforcesign(QTextStream &stream)
2721 stream.setNumberFlags(stream.numberFlags() &= ~QTextStream::ForceSign);
2726 \relates QTextStream
2728 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2729 ~QTextStream::ForcePoint) on \a stream and returns \a stream.
2731 \sa forcepoint(), noforcesign(), noshowbase(), {QTextStream manipulators}
2733 QTextStream &noforcepoint(QTextStream &stream)
2735 stream.setNumberFlags(stream.numberFlags() &= ~QTextStream::ForcePoint);
2740 \relates QTextStream
2742 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2743 QTextStream::UppercaseBase) on \a stream and returns \a stream.
2745 \sa lowercasebase(), uppercasedigits(), {QTextStream manipulators}
2747 QTextStream &uppercasebase(QTextStream &stream)
2749 stream.setNumberFlags(stream.numberFlags() | QTextStream::UppercaseBase);
2754 \relates QTextStream
2756 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2757 QTextStream::UppercaseDigits) on \a stream and returns \a stream.
2759 \sa lowercasedigits(), uppercasebase(), {QTextStream manipulators}
2761 QTextStream &uppercasedigits(QTextStream &stream)
2763 stream.setNumberFlags(stream.numberFlags() | QTextStream::UppercaseDigits);
2768 \relates QTextStream
2770 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2771 ~QTextStream::UppercaseBase) on \a stream and returns \a stream.
2773 \sa uppercasebase(), lowercasedigits(), {QTextStream manipulators}
2775 QTextStream &lowercasebase(QTextStream &stream)
2777 stream.setNumberFlags(stream.numberFlags() & ~QTextStream::UppercaseBase);
2782 \relates QTextStream
2784 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2785 ~QTextStream::UppercaseDigits) on \a stream and returns \a stream.
2787 \sa uppercasedigits(), lowercasebase(), {QTextStream manipulators}
2789 QTextStream &lowercasedigits(QTextStream &stream)
2791 stream.setNumberFlags(stream.numberFlags() & ~QTextStream::UppercaseDigits);
2796 \relates QTextStream
2798 Calls QTextStream::setRealNumberNotation(QTextStream::FixedNotation)
2799 on \a stream and returns \a stream.
2801 \sa scientific(), {QTextStream manipulators}
2803 QTextStream &fixed(QTextStream &stream)
2805 stream.setRealNumberNotation(QTextStream::FixedNotation);
2810 \relates QTextStream
2812 Calls QTextStream::setRealNumberNotation(QTextStream::ScientificNotation)
2813 on \a stream and returns \a stream.
2815 \sa fixed(), {QTextStream manipulators}
2817 QTextStream &scientific(QTextStream &stream)
2819 stream.setRealNumberNotation(QTextStream::ScientificNotation);
2824 \relates QTextStream
2826 Calls QTextStream::setFieldAlignment(QTextStream::AlignLeft)
2827 on \a stream and returns \a stream.
2829 \sa right(), center(), {QTextStream manipulators}
2831 QTextStream &left(QTextStream &stream)
2833 stream.setFieldAlignment(QTextStream::AlignLeft);
2838 \relates QTextStream
2840 Calls QTextStream::setFieldAlignment(QTextStream::AlignRight)
2841 on \a stream and returns \a stream.
2843 \sa left(), center(), {QTextStream manipulators}
2845 QTextStream &right(QTextStream &stream)
2847 stream.setFieldAlignment(QTextStream::AlignRight);
2852 \relates QTextStream
2854 Calls QTextStream::setFieldAlignment(QTextStream::AlignCenter)
2855 on \a stream and returns \a stream.
2857 \sa left(), right(), {QTextStream manipulators}
2859 QTextStream ¢er(QTextStream &stream)
2861 stream.setFieldAlignment(QTextStream::AlignCenter);
2866 \relates QTextStream
2868 Writes '\n' to the \a stream and flushes the stream.
2872 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 9
2874 Note: On Windows, all '\n' characters are written as '\r\n' if
2875 QTextStream's device or string is opened using the QIODevice::Text flag.
2877 \sa flush(), reset(), {QTextStream manipulators}
2879 QTextStream &endl(QTextStream &stream)
2881 return stream << QLatin1Char('\n') << flush;
2885 \relates QTextStream
2887 Calls QTextStream::flush() on \a stream and returns \a stream.
2889 \sa endl(), reset(), {QTextStream manipulators}
2891 QTextStream &flush(QTextStream &stream)
2898 \relates QTextStream
2900 Calls QTextStream::reset() on \a stream and returns \a stream.
2902 \sa flush(), {QTextStream manipulators}
2904 QTextStream &reset(QTextStream &stream)
2911 \relates QTextStream
2913 Calls skipWhiteSpace() on \a stream and returns \a stream.
2915 \sa {QTextStream manipulators}
2917 QTextStream &ws(QTextStream &stream)
2919 stream.skipWhiteSpace();
2924 \fn QTextStreamManipulator qSetFieldWidth(int width)
2925 \relates QTextStream
2927 Equivalent to QTextStream::setFieldWidth(\a width).
2931 \fn QTextStreamManipulator qSetPadChar(QChar ch)
2932 \relates QTextStream
2934 Equivalent to QTextStream::setPadChar(\a ch).
2938 \fn QTextStreamManipulator qSetRealNumberPrecision(int precision)
2939 \relates QTextStream
2941 Equivalent to QTextStream::setRealNumberPrecision(\a precision).
2944 #ifndef QT_NO_TEXTCODEC
2946 \relates QTextStream
2948 Toggles insertion of the Byte Order Mark on \a stream when QTextStream is
2949 used with a UTF codec.
2951 \sa QTextStream::setGenerateByteOrderMark(), {QTextStream manipulators}
2953 QTextStream &bom(QTextStream &stream)
2955 stream.setGenerateByteOrderMark(true);
2960 Sets the codec for this stream to \a codec. The codec is used for
2961 decoding any data that is read from the assigned device, and for
2962 encoding any data that is written. By default,
2963 QTextCodec::codecForLocale() is used, and automatic unicode
2964 detection is enabled.
2966 If QTextStream operates on a string, this function does nothing.
2968 \warning If you call this function while the text stream is reading
2969 from an open sequential socket, the internal buffer may still contain
2970 text decoded using the old codec.
2972 \sa codec(), setAutoDetectUnicode(), setLocale()
2974 void QTextStream::setCodec(QTextCodec *codec)
2977 qint64 seekPos = -1;
2978 if (!d->readBuffer.isEmpty()) {
2979 if (!d->device->isSequential()) {
2984 if (seekPos >=0 && !d->readBuffer.isEmpty())
2989 Sets the codec for this stream to the QTextCodec for the encoding
2990 specified by \a codecName. Common values for \c codecName include
2991 "ISO 8859-1", "UTF-8", and "UTF-16". If the encoding isn't
2992 recognized, nothing happens.
2996 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 10
2998 \sa QTextCodec::codecForName(), setLocale()
3000 void QTextStream::setCodec(const char *codecName)
3002 QTextCodec *codec = QTextCodec::codecForName(codecName);
3008 Returns the codec that is current assigned to the stream.
3010 \sa setCodec(), setAutoDetectUnicode(), locale()
3012 QTextCodec *QTextStream::codec() const
3014 Q_D(const QTextStream);
3019 If \a enabled is true, QTextStream will attempt to detect Unicode
3020 encoding by peeking into the stream data to see if it can find the
3021 UTF-16 or UTF-32 BOM (Byte Order Mark). If this mark is found, QTextStream
3022 will replace the current codec with the UTF codec.
3024 This function can be used together with setCodec(). It is common
3025 to set the codec to UTF-8, and then enable UTF-16 detection.
3027 \sa autoDetectUnicode(), setCodec()
3029 void QTextStream::setAutoDetectUnicode(bool enabled)
3032 d->autoDetectUnicode = enabled;
3036 Returns true if automatic Unicode detection is enabled, otherwise
3037 returns false. Automatic Unicode detection is enabled by default.
3039 \sa setAutoDetectUnicode(), setCodec()
3041 bool QTextStream::autoDetectUnicode() const
3043 Q_D(const QTextStream);
3044 return d->autoDetectUnicode;
3048 If \a generate is true and a UTF codec is used, QTextStream will insert
3049 the BOM (Byte Order Mark) before any data has been written to the
3050 device. If \a generate is false, no BOM will be inserted. This function
3051 must be called before any data is written. Otherwise, it does nothing.
3053 \sa generateByteOrderMark(), bom()
3055 void QTextStream::setGenerateByteOrderMark(bool generate)
3058 if (d->writeBuffer.isEmpty()) {
3060 d->writeConverterState.flags &= ~QTextCodec::IgnoreHeader;
3062 d->writeConverterState.flags |= QTextCodec::IgnoreHeader;
3067 Returns true if QTextStream is set to generate the UTF BOM (Byte Order
3068 Mark) when using a UTF codec; otherwise returns false. UTF BOM generation is
3069 set to false by default.
3071 \sa setGenerateByteOrderMark()
3073 bool QTextStream::generateByteOrderMark() const
3075 Q_D(const QTextStream);
3076 return (d->writeConverterState.flags & QTextCodec::IgnoreHeader) == 0;
3084 Sets the locale for this stream to \a locale. The specified locale is
3085 used for conversions between numbers and their string representations.
3087 The default locale is C and it is a special case - the thousands
3088 group separator is not used for backward compatibility reasons.
3092 void QTextStream::setLocale(const QLocale &locale)
3101 Returns the locale for this stream. The default locale is C.
3105 QLocale QTextStream::locale() const
3107 Q_D(const QTextStream);
3113 #ifndef QT_NO_QOBJECT
3114 #include "qtextstream.moc"