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 Note that you cannot use QTextStream::atEnd(), which returns true when you
70 have reached the end of the data stream, with stdin. The reason for this is
71 that as long as stdin doesn't give any input to the QTextStream, \c atEnd()
72 will return true even if the stdin is open and waiting for more characters.
74 Besides using QTextStream's constructors, you can also set the
75 device or string QTextStream operates on by calling setDevice() or
76 setString(). You can seek to a position by calling seek(), and
77 atEnd() will return true when there is no data left to be read. If
78 you call flush(), QTextStream will empty all data from its write
79 buffer into the device and call flush() on the device.
81 Internally, QTextStream uses a Unicode based buffer, and
82 QTextCodec is used by QTextStream to automatically support
83 different character sets. By default, QTextCodec::codecForLocale()
84 is used for reading and writing, but you can also set the codec by
85 calling setCodec(). Automatic Unicode detection is also
86 supported. When this feature is enabled (the default behavior),
87 QTextStream will detect the UTF-16 or the UTF-32 BOM (Byte Order Mark) and
88 switch to the appropriate UTF codec when reading. QTextStream
89 does not write a BOM by default, but you can enable this by calling
90 setGenerateByteOrderMark(true). When QTextStream operates on a QString
91 directly, the codec is disabled.
93 There are three general ways to use QTextStream when reading text
98 \o Chunk by chunk, by calling readLine() or readAll().
100 \o Word by word. QTextStream supports streaming into QStrings,
101 QByteArrays and char* buffers. Words are delimited by space, and
102 leading white space is automatically skipped.
104 \o Character by character, by streaming into QChar or char types.
105 This method is often used for convenient input handling when
106 parsing files, independent of character encoding and end-of-line
107 semantics. To skip white space, call skipWhiteSpace().
111 Since the text stream uses a buffer, you should not read from
112 the stream using the implementation of a superclass. For instance,
113 if you have a QFile and read from it directly using
114 QFile::readLine() instead of using the stream, the text stream's
115 internal position will be out of sync with the file's position.
117 By default, when reading numbers from a stream of text,
118 QTextStream will automatically detect the number's base
119 representation. For example, if the number starts with "0x", it is
120 assumed to be in hexadecimal form. If it starts with the digits
121 1-9, it is assumed to be in decimal form, and so on. You can set
122 the integer base, thereby disabling the automatic detection, by
123 calling setIntegerBase(). Example:
125 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 2
127 QTextStream supports many formatting options for generating text.
128 You can set the field width and pad character by calling
129 setFieldWidth() and setPadChar(). Use setFieldAlignment() to set
130 the alignment within each field. For real numbers, call
131 setRealNumberNotation() and setRealNumberPrecision() to set the
132 notation (SmartNotation, ScientificNotation, FixedNotation) and precision in
133 digits of the generated number. Some extra number formatting
134 options are also available through setNumberFlags().
136 \keyword QTextStream manipulators
138 Like \c <iostream> in the standard C++ library, QTextStream also
139 defines several global manipulator functions:
142 \header \o Manipulator \o Description
143 \row \o \c bin \o Same as setIntegerBase(2).
144 \row \o \c oct \o Same as setIntegerBase(8).
145 \row \o \c dec \o Same as setIntegerBase(10).
146 \row \o \c hex \o Same as setIntegerBase(16).
147 \row \o \c showbase \o Same as setNumberFlags(numberFlags() | ShowBase).
148 \row \o \c forcesign \o Same as setNumberFlags(numberFlags() | ForceSign).
149 \row \o \c forcepoint \o Same as setNumberFlags(numberFlags() | ForcePoint).
150 \row \o \c noshowbase \o Same as setNumberFlags(numberFlags() & ~ShowBase).
151 \row \o \c noforcesign \o Same as setNumberFlags(numberFlags() & ~ForceSign).
152 \row \o \c noforcepoint \o Same as setNumberFlags(numberFlags() & ~ForcePoint).
153 \row \o \c uppercasebase \o Same as setNumberFlags(numberFlags() | UppercaseBase).
154 \row \o \c uppercasedigits \o Same as setNumberFlags(numberFlags() | UppercaseDigits).
155 \row \o \c lowercasebase \o Same as setNumberFlags(numberFlags() & ~UppercaseBase).
156 \row \o \c lowercasedigits \o Same as setNumberFlags(numberFlags() & ~UppercaseDigits).
157 \row \o \c fixed \o Same as setRealNumberNotation(FixedNotation).
158 \row \o \c scientific \o Same as setRealNumberNotation(ScientificNotation).
159 \row \o \c left \o Same as setFieldAlignment(AlignLeft).
160 \row \o \c right \o Same as setFieldAlignment(AlignRight).
161 \row \o \c center \o Same as setFieldAlignment(AlignCenter).
162 \row \o \c endl \o Same as operator<<('\n') and flush().
163 \row \o \c flush \o Same as flush().
164 \row \o \c reset \o Same as reset().
165 \row \o \c ws \o Same as skipWhiteSpace().
166 \row \o \c bom \o Same as setGenerateByteOrderMark(true).
169 In addition, Qt provides three global manipulators that take a
170 parameter: qSetFieldWidth(), qSetPadChar(), and
171 qSetRealNumberPrecision().
173 \sa QDataStream, QIODevice, QFile, QBuffer, QTcpSocket, {Codecs Example}
176 /*! \enum QTextStream::RealNumberNotation
178 This enum specifies which notations to use for expressing \c
179 float and \c double as strings.
181 \value ScientificNotation Scientific notation (\c{printf()}'s \c %e flag).
182 \value FixedNotation Fixed-point notation (\c{printf()}'s \c %f flag).
183 \value SmartNotation Scientific or fixed-point notation, depending on which makes most sense (\c{printf()}'s \c %g flag).
185 \sa setRealNumberNotation()
188 /*! \enum QTextStream::FieldAlignment
190 This enum specifies how to align text in fields when the field is
191 wider than the text that occupies it.
193 \value AlignLeft Pad on the right side of fields.
194 \value AlignRight Pad on the left side of fields.
195 \value AlignCenter Pad on both sides of field.
196 \value AlignAccountingStyle Same as AlignRight, except that the
197 sign of a number is flush left.
199 \sa setFieldAlignment()
202 /*! \enum QTextStream::NumberFlag
204 This enum specifies various flags that can be set to affect the
205 output of integers, \c{float}s, and \c{double}s.
207 \value ShowBase Show the base as a prefix if the base
208 is 16 ("0x"), 8 ("0"), or 2 ("0b").
209 \value ForcePoint Always put the decimal separator in numbers, even if
210 there are no decimals.
211 \value ForceSign Always put the sign in numbers, even for positive numbers.
212 \value UppercaseBase Use uppercase versions of base prefixes ("0X", "0B").
213 \value UppercaseDigits Use uppercase letters for expressing
214 digits 10 to 35 instead of lowercase.
219 /*! \enum QTextStream::Status
221 This enum describes the current status of the text stream.
223 \value Ok The text stream is operating normally.
224 \value ReadPastEnd The text stream has read past the end of the
225 data in the underlying device.
226 \value ReadCorruptData The text stream has read corrupt data.
227 \value WriteFailed The text stream cannot write to the underlying device.
232 #include "qtextstream.h"
235 #include "qnumeric.h"
236 #ifndef QT_NO_TEXTCODEC
237 #include "qtextcodec.h"
242 #include "private/qlocale_p.h"
248 #if defined QTEXTSTREAM_DEBUG
253 // Returns a human readable representation of the first \a len
254 // characters in \a data.
255 static QByteArray qt_prettyDebug(const char *data, int len, int maxSize)
257 if (!data) return "(null)";
259 for (int i = 0; i < len; ++i) {
261 if (isprint(int(uchar(c)))) {
264 case '\n': out += "\\n"; break;
265 case '\r': out += "\\r"; break;
266 case '\t': out += "\\t"; break;
269 tmp.sprintf("\\x%x", (unsigned int)(unsigned char)c);
270 out += tmp.toLatin1();
283 // A precondition macro
285 #define CHECK_VALID_STREAM(x) do { \
286 if (!d->string && !d->device) { \
287 qWarning("QTextStream: No device"); \
291 // Base implementations of operator>> for ints and reals
292 #define IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(type) do { \
294 CHECK_VALID_STREAM(*this); \
296 switch (d->getNumber(&tmp)) { \
297 case QTextStreamPrivate::npsOk: \
300 case QTextStreamPrivate::npsMissingDigit: \
301 case QTextStreamPrivate::npsInvalidPrefix: \
303 setStatus(atEnd() ? QTextStream::ReadPastEnd : QTextStream::ReadCorruptData); \
306 return *this; } while (0)
308 #define IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(type) do { \
310 CHECK_VALID_STREAM(*this); \
312 if (d->getReal(&tmp)) { \
316 setStatus(atEnd() ? QTextStream::ReadPastEnd : QTextStream::ReadCorruptData); \
318 return *this; } while (0)
322 #ifndef QT_NO_QOBJECT
323 class QDeviceClosedNotifier : public QObject
327 inline QDeviceClosedNotifier()
330 inline void setupDevice(QTextStream *stream, QIODevice *device)
334 connect(device, SIGNAL(aboutToClose()), this, SLOT(flushStream()));
335 this->stream = stream;
339 inline void flushStream() { stream->flush(); }
346 //-------------------------------------------------------------------
347 class QTextStreamPrivate
349 Q_DECLARE_PUBLIC(QTextStream)
351 QTextStreamPrivate(QTextStream *q_ptr);
352 ~QTextStreamPrivate();
357 #ifndef QT_NO_QOBJECT
358 QDeviceClosedNotifier deviceClosedNotifier;
365 QIODevice::OpenMode stringOpenMode;
367 #ifndef QT_NO_TEXTCODEC
370 QTextCodec::ConverterState readConverterState;
371 QTextCodec::ConverterState writeConverterState;
372 QTextCodec::ConverterState *readConverterSavedState;
373 bool autoDetectUnicode;
377 enum TokenDelimiter {
383 QString read(int maxlen);
384 bool scan(const QChar **ptr, int *tokenLength,
385 int maxlen, TokenDelimiter delimiter);
386 inline const QChar *readPtr() const;
387 inline void consumeLastToken();
388 inline void consume(int nchars);
389 void saveConverterState(qint64 newPos);
390 void restoreToSavedConverterState();
393 // Return value type for getNumber()
394 enum NumberParsingStatus {
400 inline bool getChar(QChar *ch);
401 inline void ungetChar(const QChar &ch);
402 NumberParsingStatus getNumber(qulonglong *l);
403 bool getReal(double *f);
405 inline void write(const QString &data);
406 inline void putString(const QString &ch, bool number = false);
407 void putNumber(qulonglong number, bool negative);
410 bool fillReadBuffer(qint64 maxBytes = -1);
411 void resetReadBuffer();
412 void flushWriteBuffer();
415 int readBufferOffset;
416 int readConverterSavedStateOffset; //the offset between readBufferStartDevicePos and that start of the buffer
417 qint64 readBufferStartDevicePos;
419 // streaming parameters
420 int realNumberPrecision;
424 QTextStream::FieldAlignment fieldAlignment;
425 QTextStream::RealNumberNotation realNumberNotation;
426 QTextStream::NumberFlags numberFlags;
429 QTextStream::Status status;
438 QTextStreamPrivate::QTextStreamPrivate(QTextStream *q_ptr)
440 #ifndef QT_NO_TEXTCODEC
441 readConverterSavedState(0),
443 readConverterSavedStateOffset(0),
452 QTextStreamPrivate::~QTextStreamPrivate()
455 #ifndef QT_NO_QOBJECT
456 device->blockSignals(true);
460 #ifndef QT_NO_TEXTCODEC
461 delete readConverterSavedState;
465 #ifndef QT_NO_TEXTCODEC
466 static void resetCodecConverterStateHelper(QTextCodec::ConverterState *state)
468 state->~ConverterState();
469 new (state) QTextCodec::ConverterState;
472 static void copyConverterStateHelper(QTextCodec::ConverterState *dest,
473 const QTextCodec::ConverterState *src)
475 // ### QTextCodec::ConverterState's copy constructors and assignments are
476 // private. This function copies the structure manually.
478 dest->flags = src->flags;
479 dest->invalidChars = src->invalidChars;
480 dest->state_data[0] = src->state_data[0];
481 dest->state_data[1] = src->state_data[1];
482 dest->state_data[2] = src->state_data[2];
488 void QTextStreamPrivate::reset()
490 realNumberPrecision = 6;
493 padChar = QLatin1Char(' ');
494 fieldAlignment = QTextStream::AlignRight;
495 realNumberNotation = QTextStream::SmartNotation;
499 deleteDevice = false;
502 stringOpenMode = QIODevice::NotOpen;
504 readBufferOffset = 0;
505 readBufferStartDevicePos = 0;
508 #ifndef QT_NO_TEXTCODEC
509 codec = QTextCodec::codecForLocale();
510 resetCodecConverterStateHelper(&readConverterState);
511 resetCodecConverterStateHelper(&writeConverterState);
512 delete readConverterSavedState;
513 readConverterSavedState = 0;
514 writeConverterState.flags |= QTextCodec::IgnoreHeader;
515 autoDetectUnicode = true;
521 bool QTextStreamPrivate::fillReadBuffer(qint64 maxBytes)
523 // no buffer next to the QString itself; this function should only
524 // be called internally, for devices.
528 // handle text translation and bypass the Text flag in the device.
529 bool textModeEnabled = device->isTextModeEnabled();
531 device->setTextModeEnabled(false);
533 // read raw data into a temporary buffer
534 char buf[QTEXTSTREAM_BUFFERSIZE];
535 qint64 bytesRead = 0;
536 #if defined(Q_OS_WIN)
537 // On Windows, there is no non-blocking stdin - so we fall back to reading
538 // lines instead. If there is no QOBJECT, we read lines for all sequential
539 // devices; otherwise, we read lines only for stdin.
542 if (device->isSequential()
543 #if !defined(QT_NO_QOBJECT)
544 && (file = qobject_cast<QFile *>(device)) && file->handle() == 0
548 bytesRead = device->readLine(buf, qMin<qint64>(sizeof(buf), maxBytes));
550 bytesRead = device->readLine(buf, sizeof(buf));
555 bytesRead = device->read(buf, qMin<qint64>(sizeof(buf), maxBytes));
557 bytesRead = device->read(buf, sizeof(buf));
560 #ifndef QT_NO_TEXTCODEC
561 // codec auto detection, explicitly defaults to locale encoding if the
562 // codec has been set to 0.
563 if (!codec || autoDetectUnicode) {
564 autoDetectUnicode = false;
566 codec = QTextCodec::codecForUtfText(QByteArray::fromRawData(buf, bytesRead), codec);
568 codec = QTextCodec::codecForLocale();
569 writeConverterState.flags |= QTextCodec::IgnoreHeader;
572 #if defined (QTEXTSTREAM_DEBUG)
573 qDebug("QTextStreamPrivate::fillReadBuffer(), using %s codec",
574 codec->name().constData());
578 #if defined (QTEXTSTREAM_DEBUG)
579 qDebug("QTextStreamPrivate::fillReadBuffer(), device->read(\"%s\", %d) == %d",
580 qt_prettyDebug(buf, qMin(32,int(bytesRead)) , int(bytesRead)).constData(), sizeof(buf), int(bytesRead));
586 int oldReadBufferSize = readBuffer.size();
587 #ifndef QT_NO_TEXTCODEC
588 // convert to unicode
589 readBuffer += codec->toUnicode(buf, bytesRead, &readConverterState);
591 readBuffer += QString::fromLatin1(QByteArray(buf, bytesRead).constData());
594 // reset the Text flag.
596 device->setTextModeEnabled(true);
598 // remove all '\r\n' in the string.
599 if (readBuffer.size() > oldReadBufferSize && textModeEnabled) {
600 QChar CR = QLatin1Char('\r');
601 QChar *writePtr = readBuffer.data() + oldReadBufferSize;
602 QChar *readPtr = readBuffer.data() + oldReadBufferSize;
603 QChar *endPtr = readBuffer.data() + readBuffer.size();
605 int n = oldReadBufferSize;
606 if (readPtr < endPtr) {
607 // Cut-off to avoid unnecessary self-copying.
608 while (*readPtr++ != CR) {
610 if (++writePtr == endPtr)
614 while (readPtr < endPtr) {
615 QChar ch = *readPtr++;
619 if (n < readBufferOffset)
625 readBuffer.resize(writePtr - readBuffer.data());
628 #if defined (QTEXTSTREAM_DEBUG)
629 qDebug("QTextStreamPrivate::fillReadBuffer() read %d bytes from device. readBuffer = [%s]", int(bytesRead),
630 qt_prettyDebug(readBuffer.toLatin1(), readBuffer.size(), readBuffer.size()).data());
637 void QTextStreamPrivate::resetReadBuffer()
640 readBufferOffset = 0;
641 readBufferStartDevicePos = (device ? device->pos() : 0);
646 void QTextStreamPrivate::flushWriteBuffer()
648 // no buffer next to the QString itself; this function should only
649 // be called internally, for devices.
650 if (string || !device)
653 // Stream went bye-bye already. Appending further data may succeed again,
654 // but would create a corrupted stream anyway.
655 if (status != QTextStream::Ok)
658 if (writeBuffer.isEmpty())
661 #if defined (Q_OS_WIN)
662 // handle text translation and bypass the Text flag in the device.
663 bool textModeEnabled = device->isTextModeEnabled();
664 if (textModeEnabled) {
665 device->setTextModeEnabled(false);
666 writeBuffer.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
670 #ifndef QT_NO_TEXTCODEC
672 codec = QTextCodec::codecForLocale();
673 #if defined (QTEXTSTREAM_DEBUG)
674 qDebug("QTextStreamPrivate::flushWriteBuffer(), using %s codec (%s generating BOM)",
675 codec->name().constData(), writeConverterState.flags & QTextCodec::IgnoreHeader ? "not" : "");
678 // convert from unicode to raw data
679 QByteArray data = codec->fromUnicode(writeBuffer.data(), writeBuffer.size(), &writeConverterState);
681 QByteArray data = writeBuffer.toLocal8Bit();
685 // write raw data to the device
686 qint64 bytesWritten = device->write(data);
687 #if defined (QTEXTSTREAM_DEBUG)
688 qDebug("QTextStreamPrivate::flushWriteBuffer(), device->write(\"%s\") == %d",
689 qt_prettyDebug(data.constData(), qMin(data.size(),32), data.size()).constData(), int(bytesWritten));
691 if (bytesWritten <= 0) {
692 status = QTextStream::WriteFailed;
696 #if defined (Q_OS_WIN)
697 // replace the text flag
699 device->setTextModeEnabled(true);
703 #ifndef QT_NO_QOBJECT
704 QFile *file = qobject_cast<QFile *>(device);
705 bool flushed = !file || file->flush();
710 #if defined (QTEXTSTREAM_DEBUG)
711 qDebug("QTextStreamPrivate::flushWriteBuffer() wrote %d bytes",
714 if (!flushed || bytesWritten != qint64(data.size()))
715 status = QTextStream::WriteFailed;
718 QString QTextStreamPrivate::read(int maxlen)
722 lastTokenSize = qMin(maxlen, string->size() - stringOffset);
723 ret = string->mid(stringOffset, lastTokenSize);
725 while (readBuffer.size() - readBufferOffset < maxlen && fillReadBuffer()) ;
726 lastTokenSize = qMin(maxlen, readBuffer.size() - readBufferOffset);
727 ret = readBuffer.mid(readBufferOffset, lastTokenSize);
731 #if defined (QTEXTSTREAM_DEBUG)
732 qDebug("QTextStreamPrivate::read() maxlen = %d, token length = %d", maxlen, ret.length());
739 Scans no more than \a maxlen QChars in the current buffer for the
740 first \a delimiter. Stores a pointer to the start offset of the
741 token in \a ptr, and the length in QChars in \a length.
743 bool QTextStreamPrivate::scan(const QChar **ptr, int *length, int maxlen, TokenDelimiter delimiter)
747 bool consumeDelimiter = false;
748 bool foundToken = false;
749 int startOffset = device ? readBufferOffset : stringOffset;
752 bool canStillReadFromDevice = true;
757 chPtr = readBuffer.constData();
758 endOffset = readBuffer.size();
760 chPtr = string->constData();
761 endOffset = string->size();
763 chPtr += startOffset;
765 for (; !foundToken && startOffset < endOffset && (!maxlen || totalSize < maxlen); ++startOffset) {
766 const QChar ch = *chPtr++;
783 if (ch == QLatin1Char('\n')) {
785 delimSize = (lastChar == QLatin1Char('\r')) ? 2 : 1;
786 consumeDelimiter = true;
793 && (!maxlen || totalSize < maxlen)
794 && (device && (canStillReadFromDevice = fillReadBuffer())));
796 // if the token was not found, but we reached the end of input,
797 // then we accept what we got. if we are not at the end of input,
799 if (!foundToken && (!maxlen || totalSize < maxlen)
801 || (string && stringOffset + totalSize < string->size())
802 || (device && !device->atEnd() && canStillReadFromDevice))) {
803 #if defined (QTEXTSTREAM_DEBUG)
804 qDebug("QTextStreamPrivate::scan() did not find the token.");
809 // if we find a '\r' at the end of the data when reading lines,
810 // don't make it part of the line.
811 if (delimiter == EndOfLine && totalSize > 0 && !foundToken) {
812 if (((string && stringOffset + totalSize == string->size()) || (device && device->atEnd()))
813 && lastChar == QLatin1Char('\r')) {
814 consumeDelimiter = true;
819 // set the read offset and length of the token
821 *length = totalSize - delimSize;
825 // update last token size. the callee will call consumeLastToken() when
827 lastTokenSize = totalSize;
828 if (!consumeDelimiter)
829 lastTokenSize -= delimSize;
831 #if defined (QTEXTSTREAM_DEBUG)
832 qDebug("QTextStreamPrivate::scan(%p, %p, %d, %x) token length = %d, delimiter = %d",
833 ptr, length, maxlen, (int)delimiter, totalSize - delimSize, delimSize);
840 inline const QChar *QTextStreamPrivate::readPtr() const
842 Q_ASSERT(readBufferOffset <= readBuffer.size());
844 return string->constData() + stringOffset;
845 return readBuffer.constData() + readBufferOffset;
850 inline void QTextStreamPrivate::consumeLastToken()
853 consume(lastTokenSize);
859 inline void QTextStreamPrivate::consume(int size)
861 #if defined (QTEXTSTREAM_DEBUG)
862 qDebug("QTextStreamPrivate::consume(%d)", size);
865 stringOffset += size;
866 if (stringOffset > string->size())
867 stringOffset = string->size();
869 readBufferOffset += size;
870 if (readBufferOffset >= readBuffer.size()) {
871 readBufferOffset = 0;
873 saveConverterState(device->pos());
874 } else if (readBufferOffset > QTEXTSTREAM_BUFFERSIZE) {
875 readBuffer = readBuffer.remove(0,readBufferOffset);
876 readConverterSavedStateOffset += readBufferOffset;
877 readBufferOffset = 0;
884 inline void QTextStreamPrivate::saveConverterState(qint64 newPos)
886 #ifndef QT_NO_TEXTCODEC
887 if (readConverterState.d) {
888 // converter cannot be copied, so don't save anything
889 // don't update readBufferStartDevicePos either
893 if (!readConverterSavedState)
894 readConverterSavedState = new QTextCodec::ConverterState;
895 copyConverterStateHelper(readConverterSavedState, &readConverterState);
898 readBufferStartDevicePos = newPos;
899 readConverterSavedStateOffset = 0;
904 inline void QTextStreamPrivate::restoreToSavedConverterState()
906 #ifndef QT_NO_TEXTCODEC
907 if (readConverterSavedState) {
908 // we have a saved state
909 // that means the converter can be copied
910 copyConverterStateHelper(&readConverterState, readConverterSavedState);
912 // the only state we could save was the initial
914 resetCodecConverterStateHelper(&readConverterState);
921 inline void QTextStreamPrivate::write(const QString &data)
924 // ### What about seek()??
925 string->append(data);
928 if (writeBuffer.size() > QTEXTSTREAM_BUFFERSIZE)
935 inline bool QTextStreamPrivate::getChar(QChar *ch)
937 if ((string && stringOffset == string->size())
938 || (device && readBuffer.isEmpty() && !fillReadBuffer())) {
951 inline void QTextStreamPrivate::ungetChar(const QChar &ch)
954 if (stringOffset == 0)
957 (*string)[--stringOffset] = ch;
961 if (readBufferOffset == 0) {
962 readBuffer.prepend(ch);
966 readBuffer[--readBufferOffset] = ch;
971 inline void QTextStreamPrivate::putString(const QString &s, bool number)
976 int padSize = fieldWidth - s.size();
978 QString pad(padSize, padChar);
979 if (fieldAlignment == QTextStream::AlignLeft) {
980 tmp.append(QString(padSize, padChar));
981 } else if (fieldAlignment == QTextStream::AlignRight
982 || fieldAlignment == QTextStream::AlignAccountingStyle) {
983 tmp.prepend(QString(padSize, padChar));
984 if (fieldAlignment == QTextStream::AlignAccountingStyle && number) {
985 const QChar sign = s.size() > 0 ? s.at(0) : QChar();
986 if (sign == locale.negativeSign() || sign == locale.positiveSign()) {
987 QChar *data = tmp.data();
988 data[padSize] = tmp.at(0);
992 } else if (fieldAlignment == QTextStream::AlignCenter) {
993 tmp.prepend(QString(padSize/2, padChar));
994 tmp.append(QString(padSize - padSize/2, padChar));
998 #if defined (QTEXTSTREAM_DEBUG)
999 QByteArray a = s.toUtf8();
1000 QByteArray b = tmp.toUtf8();
1001 qDebug("QTextStreamPrivate::putString(\"%s\") calls write(\"%s\")",
1002 qt_prettyDebug(a.constData(), a.size(), qMax(16, a.size())).constData(),
1003 qt_prettyDebug(b.constData(), b.size(), qMax(16, b.size())).constData());
1009 Constructs a QTextStream. Before you can use it for reading or
1010 writing, you must assign a device or a string.
1012 \sa setDevice(), setString()
1014 QTextStream::QTextStream()
1015 : d_ptr(new QTextStreamPrivate(this))
1017 #if defined (QTEXTSTREAM_DEBUG)
1018 qDebug("QTextStream::QTextStream()");
1025 Constructs a QTextStream that operates on \a device.
1027 QTextStream::QTextStream(QIODevice *device)
1028 : d_ptr(new QTextStreamPrivate(this))
1030 #if defined (QTEXTSTREAM_DEBUG)
1031 qDebug("QTextStream::QTextStream(QIODevice *device == *%p)",
1036 #ifndef QT_NO_QOBJECT
1037 d->deviceClosedNotifier.setupDevice(this, d->device);
1043 Constructs a QTextStream that operates on \a string, using \a
1044 openMode to define the open mode.
1046 QTextStream::QTextStream(QString *string, QIODevice::OpenMode openMode)
1047 : d_ptr(new QTextStreamPrivate(this))
1049 #if defined (QTEXTSTREAM_DEBUG)
1050 qDebug("QTextStream::QTextStream(QString *string == *%p, openMode = %d)",
1051 string, int(openMode));
1055 d->stringOpenMode = openMode;
1060 Constructs a QTextStream that operates on \a array, using \a
1061 openMode to define the open mode. Internally, the array is wrapped
1064 QTextStream::QTextStream(QByteArray *array, QIODevice::OpenMode openMode)
1065 : d_ptr(new QTextStreamPrivate(this))
1067 #if defined (QTEXTSTREAM_DEBUG)
1068 qDebug("QTextStream::QTextStream(QByteArray *array == *%p, openMode = %d)",
1069 array, int(openMode));
1072 d->device = new QBuffer(array);
1073 d->device->open(openMode);
1074 d->deleteDevice = true;
1075 #ifndef QT_NO_QOBJECT
1076 d->deviceClosedNotifier.setupDevice(this, d->device);
1082 Constructs a QTextStream that operates on \a array, using \a
1083 openMode to define the open mode. The array is accessed as
1084 read-only, regardless of the values in \a openMode.
1086 This constructor is convenient for working on constant
1089 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 3
1091 QTextStream::QTextStream(const QByteArray &array, QIODevice::OpenMode openMode)
1092 : d_ptr(new QTextStreamPrivate(this))
1094 #if defined (QTEXTSTREAM_DEBUG)
1095 qDebug("QTextStream::QTextStream(const QByteArray &array == *(%p), openMode = %d)",
1096 &array, int(openMode));
1098 QBuffer *buffer = new QBuffer;
1099 buffer->setData(array);
1100 buffer->open(openMode);
1104 d->deleteDevice = true;
1105 #ifndef QT_NO_QOBJECT
1106 d->deviceClosedNotifier.setupDevice(this, d->device);
1112 Constructs a QTextStream that operates on \a fileHandle, using \a
1113 openMode to define the open mode. Internally, a QFile is created
1114 to handle the FILE pointer.
1116 This constructor is useful for working directly with the common
1117 FILE based input and output streams: stdin, stdout and stderr. Example:
1119 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 4
1122 QTextStream::QTextStream(FILE *fileHandle, QIODevice::OpenMode openMode)
1123 : d_ptr(new QTextStreamPrivate(this))
1125 #if defined (QTEXTSTREAM_DEBUG)
1126 qDebug("QTextStream::QTextStream(FILE *fileHandle = %p, openMode = %d)",
1127 fileHandle, int(openMode));
1129 QFile *file = new QFile;
1130 file->open(fileHandle, openMode);
1134 d->deleteDevice = true;
1135 #ifndef QT_NO_QOBJECT
1136 d->deviceClosedNotifier.setupDevice(this, d->device);
1142 Destroys the QTextStream.
1144 If the stream operates on a device, flush() will be called
1145 implicitly. Otherwise, the device is unaffected.
1147 QTextStream::~QTextStream()
1150 #if defined (QTEXTSTREAM_DEBUG)
1151 qDebug("QTextStream::~QTextStream()");
1153 if (!d->writeBuffer.isEmpty())
1154 d->flushWriteBuffer();
1158 Resets QTextStream's formatting options, bringing it back to its
1159 original constructed state. The device, string and any buffered
1160 data is left untouched.
1162 void QTextStream::reset()
1166 d->realNumberPrecision = 6;
1169 d->padChar = QLatin1Char(' ');
1170 d->fieldAlignment = QTextStream::AlignRight;
1171 d->realNumberNotation = QTextStream::SmartNotation;
1176 Flushes any buffered data waiting to be written to the device.
1178 If QTextStream operates on a string, this function does nothing.
1180 void QTextStream::flush()
1183 d->flushWriteBuffer();
1187 Seeks to the position \a pos in the device. Returns true on
1188 success; otherwise returns false.
1190 bool QTextStream::seek(qint64 pos)
1193 d->lastTokenSize = 0;
1196 // Empty the write buffer
1197 d->flushWriteBuffer();
1198 if (!d->device->seek(pos))
1200 d->resetReadBuffer();
1202 #ifndef QT_NO_TEXTCODEC
1203 // Reset the codec converter states.
1204 resetCodecConverterStateHelper(&d->readConverterState);
1205 resetCodecConverterStateHelper(&d->writeConverterState);
1206 delete d->readConverterSavedState;
1207 d->readConverterSavedState = 0;
1208 d->writeConverterState.flags |= QTextCodec::IgnoreHeader;
1214 if (d->string && pos <= d->string->size()) {
1215 d->stringOffset = int(pos);
1224 Returns the device position corresponding to the current position of the
1225 stream, or -1 if an error occurs (e.g., if there is no device or string,
1226 or if there's a device error).
1228 Because QTextStream is buffered, this function may have to
1229 seek the device to reconstruct a valid device position. This
1230 operation can be expensive, so you may want to avoid calling this
1231 function in a tight loop.
1235 qint64 QTextStream::pos() const
1237 Q_D(const QTextStream);
1240 if (d->readBuffer.isEmpty())
1241 return d->device->pos();
1242 if (d->device->isSequential())
1246 if (!d->device->seek(d->readBufferStartDevicePos))
1249 // Reset the read buffer
1250 QTextStreamPrivate *thatd = const_cast<QTextStreamPrivate *>(d);
1251 thatd->readBuffer.clear();
1253 #ifndef QT_NO_TEXTCODEC
1254 thatd->restoreToSavedConverterState();
1255 if (d->readBufferStartDevicePos == 0)
1256 thatd->autoDetectUnicode = true;
1259 // Rewind the device to get to the current position Ensure that
1260 // readBufferOffset is unaffected by fillReadBuffer()
1261 int oldReadBufferOffset = d->readBufferOffset + d->readConverterSavedStateOffset;
1262 while (d->readBuffer.size() < oldReadBufferOffset) {
1263 if (!thatd->fillReadBuffer(1))
1266 thatd->readBufferOffset = oldReadBufferOffset;
1267 thatd->readConverterSavedStateOffset = 0;
1269 // Return the device position.
1270 return d->device->pos();
1274 return d->stringOffset;
1276 qWarning("QTextStream::pos: no device");
1281 Reads and discards whitespace from the stream until either a
1282 non-space character is detected, or until atEnd() returns
1283 true. This function is useful when reading a stream character by
1286 Whitespace characters are all characters for which
1287 QChar::isSpace() returns true.
1291 void QTextStream::skipWhiteSpace()
1294 CHECK_VALID_STREAM(Q_VOID);
1295 d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
1296 d->consumeLastToken();
1300 Sets the current device to \a device. If a device has already been
1301 assigned, QTextStream will call flush() before the old device is
1304 \note This function resets locale to the default locale ('C')
1305 and codec to the default codec, QTextCodec::codecForLocale().
1307 \sa device(), setString()
1309 void QTextStream::setDevice(QIODevice *device)
1313 if (d->deleteDevice) {
1314 #ifndef QT_NO_QOBJECT
1315 d->deviceClosedNotifier.disconnect();
1318 d->deleteDevice = false;
1324 d->resetReadBuffer();
1325 #ifndef QT_NO_QOBJECT
1326 d->deviceClosedNotifier.setupDevice(this, d->device);
1331 Returns the current device associated with the QTextStream,
1332 or 0 if no device has been assigned.
1334 \sa setDevice(), string()
1336 QIODevice *QTextStream::device() const
1338 Q_D(const QTextStream);
1343 Sets the current string to \a string, using the given \a
1344 openMode. If a device has already been assigned, QTextStream will
1345 call flush() before replacing it.
1347 \sa string(), setDevice()
1349 void QTextStream::setString(QString *string, QIODevice::OpenMode openMode)
1353 if (d->deleteDevice) {
1354 #ifndef QT_NO_QOBJECT
1355 d->deviceClosedNotifier.disconnect();
1356 d->device->blockSignals(true);
1359 d->deleteDevice = false;
1365 d->stringOpenMode = openMode;
1369 Returns the current string assigned to the QTextStream, or 0 if no
1370 string has been assigned.
1372 \sa setString(), device()
1374 QString *QTextStream::string() const
1376 Q_D(const QTextStream);
1381 Sets the field alignment to \a mode. When used together with
1382 setFieldWidth(), this function allows you to generate formatted
1383 output with text aligned to the left, to the right or center
1386 \sa fieldAlignment(), setFieldWidth()
1388 void QTextStream::setFieldAlignment(FieldAlignment mode)
1391 d->fieldAlignment = mode;
1395 Returns the current field alignment.
1397 \sa setFieldAlignment(), fieldWidth()
1399 QTextStream::FieldAlignment QTextStream::fieldAlignment() const
1401 Q_D(const QTextStream);
1402 return d->fieldAlignment;
1406 Sets the pad character to \a ch. The default value is the ASCII
1407 space character (' '), or QChar(0x20). This character is used to
1408 fill in the space in fields when generating text.
1412 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 5
1414 The string \c s contains:
1416 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 6
1418 \sa padChar(), setFieldWidth()
1420 void QTextStream::setPadChar(QChar ch)
1427 Returns the current pad character.
1429 \sa setPadChar(), setFieldWidth()
1431 QChar QTextStream::padChar() const
1433 Q_D(const QTextStream);
1438 Sets the current field width to \a width. If \a width is 0 (the
1439 default), the field width is equal to the length of the generated
1442 \note The field width applies to every element appended to this
1443 stream after this function has been called (e.g., it also pads
1444 endl). This behavior is different from similar classes in the STL,
1445 where the field width only applies to the next element.
1447 \sa fieldWidth(), setPadChar()
1449 void QTextStream::setFieldWidth(int width)
1452 d->fieldWidth = width;
1456 Returns the current field width.
1460 int QTextStream::fieldWidth() const
1462 Q_D(const QTextStream);
1463 return d->fieldWidth;
1467 Sets the current number flags to \a flags. \a flags is a set of
1468 flags from the NumberFlag enum, and describes options for
1469 formatting generated code (e.g., whether or not to always write
1470 the base or sign of a number).
1472 \sa numberFlags(), setIntegerBase(), setRealNumberNotation()
1474 void QTextStream::setNumberFlags(NumberFlags flags)
1477 d->numberFlags = flags;
1481 Returns the current number flags.
1483 \sa setNumberFlags(), integerBase(), realNumberNotation()
1485 QTextStream::NumberFlags QTextStream::numberFlags() const
1487 Q_D(const QTextStream);
1488 return d->numberFlags;
1492 Sets the base of integers to \a base, both for reading and for
1493 generating numbers. \a base can be either 2 (binary), 8 (octal),
1494 10 (decimal) or 16 (hexadecimal). If \a base is 0, QTextStream
1495 will attempt to detect the base by inspecting the data on the
1496 stream. When generating numbers, QTextStream assumes base is 10
1497 unless the base has been set explicitly.
1499 \sa integerBase(), QString::number(), setNumberFlags()
1501 void QTextStream::setIntegerBase(int base)
1504 d->integerBase = base;
1508 Returns the current base of integers. 0 means that the base is
1509 detected when reading, or 10 (decimal) when generating numbers.
1511 \sa setIntegerBase(), QString::number(), numberFlags()
1513 int QTextStream::integerBase() const
1515 Q_D(const QTextStream);
1516 return d->integerBase;
1520 Sets the real number notation to \a notation (SmartNotation,
1521 FixedNotation, ScientificNotation). When reading and generating
1522 numbers, QTextStream uses this value to detect the formatting of
1525 \sa realNumberNotation(), setRealNumberPrecision(), setNumberFlags(), setIntegerBase()
1527 void QTextStream::setRealNumberNotation(RealNumberNotation notation)
1530 d->realNumberNotation = notation;
1534 Returns the current real number notation.
1536 \sa setRealNumberNotation(), realNumberPrecision(), numberFlags(), integerBase()
1538 QTextStream::RealNumberNotation QTextStream::realNumberNotation() const
1540 Q_D(const QTextStream);
1541 return d->realNumberNotation;
1545 Sets the precision of real numbers to \a precision. This value
1546 describes the number of fraction digits QTextStream should
1547 write when generating real numbers.
1549 The precision cannot be a negative value. The default value is 6.
1551 \sa realNumberPrecision(), setRealNumberNotation()
1553 void QTextStream::setRealNumberPrecision(int precision)
1556 if (precision < 0) {
1557 qWarning("QTextStream::setRealNumberPrecision: Invalid precision (%d)", precision);
1558 d->realNumberPrecision = 6;
1561 d->realNumberPrecision = precision;
1565 Returns the current real number precision, or the number of fraction
1566 digits QTextStream will write when generating real numbers.
1568 \sa setRealNumberNotation(), realNumberNotation(), numberFlags(), integerBase()
1570 int QTextStream::realNumberPrecision() const
1572 Q_D(const QTextStream);
1573 return d->realNumberPrecision;
1577 Returns the status of the text stream.
1579 \sa QTextStream::Status, setStatus(), resetStatus()
1582 QTextStream::Status QTextStream::status() const
1584 Q_D(const QTextStream);
1591 Resets the status of the text stream.
1593 \sa QTextStream::Status, status(), setStatus()
1595 void QTextStream::resetStatus()
1604 Sets the status of the text stream to the \a status given.
1606 Subsequent calls to setStatus() are ignored until resetStatus()
1609 \sa Status status() resetStatus()
1611 void QTextStream::setStatus(Status status)
1614 if (d->status == Ok)
1619 Returns true if there is no more data to be read from the
1620 QTextStream; otherwise returns false. This is similar to, but not
1621 the same as calling QIODevice::atEnd(), as QTextStream also takes
1622 into account its internal Unicode buffer.
1624 bool QTextStream::atEnd() const
1626 Q_D(const QTextStream);
1627 CHECK_VALID_STREAM(true);
1630 return d->string->size() == d->stringOffset;
1631 return d->readBuffer.isEmpty() && d->device->atEnd();
1635 Reads the entire content of the stream, and returns it as a
1636 QString. Avoid this function when working on large files, as it
1637 will consume a significant amount of memory.
1639 Calling readLine() is better if you do not know how much data is
1644 QString QTextStream::readAll()
1647 CHECK_VALID_STREAM(QString());
1649 return d->read(INT_MAX);
1653 Reads one line of text from the stream, and returns it as a
1654 QString. The maximum allowed line length is set to \a maxlen. If
1655 the stream contains lines longer than this, then the lines will be
1656 split after \a maxlen characters and returned in parts.
1658 If \a maxlen is 0, the lines can be of any length. A common value
1659 for \a maxlen is 75.
1661 The returned line has no trailing end-of-line characters ("\\n"
1662 or "\\r\\n"), so calling QString::trimmed() is unnecessary.
1664 If the stream has read to the end of the file, readLine() will return a
1665 null QString. For strings, or for devices that support it, you can
1666 explicitly test for the end of the stream using atEnd().
1668 \sa readAll(), QIODevice::readLine()
1670 QString QTextStream::readLine(qint64 maxlen)
1673 CHECK_VALID_STREAM(QString());
1675 const QChar *readPtr;
1677 if (!d->scan(&readPtr, &length, int(maxlen), QTextStreamPrivate::EndOfLine))
1680 QString tmp = QString(readPtr, length);
1681 d->consumeLastToken();
1688 Reads at most \a maxlen characters from the stream, and returns the data
1691 \sa readAll(), readLine(), QIODevice::read()
1693 QString QTextStream::read(qint64 maxlen)
1696 CHECK_VALID_STREAM(QString());
1699 return QString::fromLatin1(""); // empty, not null
1701 return d->read(int(maxlen));
1706 QTextStreamPrivate::NumberParsingStatus QTextStreamPrivate::getNumber(qulonglong *ret)
1708 scan(0, 0, 0, NotSpace);
1711 // detect int encoding
1712 int base = integerBase;
1716 return npsInvalidPrefix;
1717 if (ch == QLatin1Char('0')) {
1719 if (!getChar(&ch2)) {
1720 // Result is the number 0
1724 ch2 = ch2.toLower();
1726 if (ch2 == QLatin1Char('x')) {
1728 } else if (ch2 == QLatin1Char('b')) {
1730 } else if (ch2.isDigit() && ch2.digitValue() >= 0 && ch2.digitValue() <= 7) {
1736 } else if (ch == locale.negativeSign() || ch == locale.positiveSign() || ch.isDigit()) {
1740 return npsInvalidPrefix;
1743 // State of the stream is now the same as on entry
1744 // (cursor is at prefix),
1745 // and local variable 'base' has been set appropriately.
1751 QChar pf1, pf2, dig;
1752 // Parse prefix '0b'
1753 if (!getChar(&pf1) || pf1 != QLatin1Char('0'))
1754 return npsInvalidPrefix;
1755 if (!getChar(&pf2) || pf2.toLower() != QLatin1Char('b'))
1756 return npsInvalidPrefix;
1759 while (getChar(&dig)) {
1760 int n = dig.toLower().unicode();
1761 if (n == '0' || n == '1') {
1771 // Unwind the prefix and abort
1774 return npsMissingDigit;
1781 if (!getChar(&pf) || pf != QLatin1Char('0'))
1782 return npsInvalidPrefix;
1785 while (getChar(&dig)) {
1786 int n = dig.toLower().unicode();
1787 if (n >= '0' && n <= '7') {
1797 // Unwind the prefix and abort
1799 return npsMissingDigit;
1804 // Parse sign (or first digit)
1807 if (!getChar(&sign))
1808 return npsMissingDigit;
1809 if (sign != locale.negativeSign() && sign != locale.positiveSign()) {
1810 if (!sign.isDigit()) {
1812 return npsMissingDigit;
1814 val += sign.digitValue();
1819 while (getChar(&ch)) {
1822 val += ch.digitValue();
1823 } else if (locale != QLocale::c() && ch == locale.groupSeparator()) {
1832 return npsMissingDigit;
1833 if (sign == locale.negativeSign()) {
1834 qlonglong ival = qlonglong(val);
1837 val = qulonglong(ival);
1842 QChar pf1, pf2, dig;
1843 // Parse prefix ' 0x'
1844 if (!getChar(&pf1) || pf1 != QLatin1Char('0'))
1845 return npsInvalidPrefix;
1846 if (!getChar(&pf2) || pf2.toLower() != QLatin1Char('x'))
1847 return npsInvalidPrefix;
1850 while (getChar(&dig)) {
1851 int n = dig.toLower().unicode();
1852 if (n >= '0' && n <= '9') {
1855 } else if (n >= 'a' && n <= 'f') {
1857 val += 10 + (n - 'a');
1865 return npsMissingDigit;
1870 // Unsupported integerBase
1871 return npsInvalidPrefix;
1882 bool QTextStreamPrivate::getReal(double *f)
1884 // We use a table-driven FSM to parse floating point numbers
1885 // strtod() cannot be used directly since we may be reading from a
1916 static const uchar table[13][10] = {
1917 // None InputSign InputDigit InputDot InputExp InputI InputN InputF InputA InputT
1918 { 0, Sign, Mantissa, Dot, 0, Inf1, Nan1, 0, 0, 0 }, // 0 Init
1919 { 0, 0, Mantissa, Dot, 0, Inf1, Nan1, 0, 0, 0 }, // 1 Sign
1920 { Done, Done, Mantissa, Dot, ExpMark, 0, 0, 0, 0, 0 }, // 2 Mantissa
1921 { 0, 0, Abscissa, 0, 0, 0, 0, 0, 0, 0 }, // 3 Dot
1922 { Done, Done, Abscissa, Done, ExpMark, 0, 0, 0, 0, 0 }, // 4 Abscissa
1923 { 0, ExpSign, Exponent, 0, 0, 0, 0, 0, 0, 0 }, // 5 ExpMark
1924 { 0, 0, Exponent, 0, 0, 0, 0, 0, 0, 0 }, // 6 ExpSign
1925 { Done, Done, Exponent, Done, Done, 0, 0, 0, 0, 0 }, // 7 Exponent
1926 { 0, 0, 0, 0, 0, 0, 0, 0, Nan2, 0 }, // 8 Nan1
1927 { 0, 0, 0, 0, 0, 0, NanInf, 0, 0, 0 }, // 9 Nan2
1928 { 0, 0, 0, 0, 0, 0, Inf2, 0, 0, 0 }, // 10 Inf1
1929 { 0, 0, 0, 0, 0, 0, 0, NanInf, 0, 0 }, // 11 Inf2
1930 { Done, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // 11 NanInf
1933 ParserState state = Init;
1934 InputToken input = None;
1936 scan(0, 0, 0, NotSpace);
1939 const int BufferSize = 128;
1940 char buf[BufferSize];
1944 while (getChar(&c)) {
1945 switch (c.unicode()) {
1946 case '0': case '1': case '2': case '3': case '4':
1947 case '5': case '6': case '7': case '8': case '9':
1966 QChar lc = c.toLower();
1967 if (lc == locale.decimalPoint().toLower())
1969 else if (lc == locale.exponential().toLower())
1971 else if (lc == locale.negativeSign().toLower()
1972 || lc == locale.positiveSign().toLower())
1974 else if (locale != QLocale::c() // backward-compatibility
1975 && lc == locale.groupSeparator().toLower())
1976 input = InputDigit; // well, it isn't a digit, but no one cares.
1983 state = ParserState(table[state][input]);
1985 if (state == Init || state == Done || i > (BufferSize - 5)) {
1987 if (i > (BufferSize - 5)) { // ignore rest of digits
1988 while (getChar(&c)) {
1998 buf[i++] = c.toLatin1();
2007 // backward-compatibility. Old implementation supported +nan/-nan
2008 // for some reason. QLocale only checks for lower-case
2009 // nan/+inf/-inf, so here we also check for uppercase and mixed
2011 if (!qstricmp(buf, "nan") || !qstricmp(buf, "+nan") || !qstricmp(buf, "-nan")) {
2014 } else if (!qstricmp(buf, "+inf") || !qstricmp(buf, "inf")) {
2017 } else if (!qstricmp(buf, "-inf")) {
2022 *f = locale.toDouble(QString::fromLatin1(buf), &ok);
2027 Reads a character from the stream and stores it in \a c. Returns a
2028 reference to the QTextStream, so several operators can be
2031 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 7
2033 Whitespace is \e not skipped.
2036 QTextStream &QTextStream::operator>>(QChar &c)
2039 CHECK_VALID_STREAM(*this);
2040 d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
2041 if (!d->getChar(&c))
2042 setStatus(ReadPastEnd);
2049 Reads a character from the stream and stores it in \a c. The
2050 character from the stream is converted to ISO-5589-1 before it is
2053 \sa QChar::toLatin1()
2055 QTextStream &QTextStream::operator>>(char &c)
2064 Reads an integer from the stream and stores it in \a i, then
2065 returns a reference to the QTextStream. The number is cast to
2066 the correct type before it is stored. If no number was detected on
2067 the stream, \a i is set to 0.
2069 By default, QTextStream will attempt to detect the base of the
2070 number using the following rules:
2073 \header \o Prefix \o Base
2074 \row \o "0b" or "0B" \o 2 (binary)
2075 \row \o "0" followed by "0-7" \o 8 (octal)
2076 \row \o "0" otherwise \o 10 (decimal)
2077 \row \o "0x" or "0X" \o 16 (hexadecimal)
2078 \row \o "1" to "9" \o 10 (decimal)
2081 By calling setIntegerBase(), you can specify the integer base
2082 explicitly. This will disable the auto-detection, and speed up
2083 QTextStream slightly.
2085 Leading whitespace is skipped.
2087 QTextStream &QTextStream::operator>>(signed short &i)
2089 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(signed short);
2095 Stores the integer in the unsigned short \a i.
2097 QTextStream &QTextStream::operator>>(unsigned short &i)
2099 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(unsigned short);
2105 Stores the integer in the signed int \a i.
2107 QTextStream &QTextStream::operator>>(signed int &i)
2109 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(signed int);
2115 Stores the integer in the unsigned int \a i.
2117 QTextStream &QTextStream::operator>>(unsigned int &i)
2119 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(unsigned int);
2125 Stores the integer in the signed long \a i.
2127 QTextStream &QTextStream::operator>>(signed long &i)
2129 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(signed long);
2135 Stores the integer in the unsigned long \a i.
2137 QTextStream &QTextStream::operator>>(unsigned long &i)
2139 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(unsigned long);
2145 Stores the integer in the qlonglong \a i.
2147 QTextStream &QTextStream::operator>>(qlonglong &i)
2149 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(qlonglong);
2155 Stores the integer in the qulonglong \a i.
2157 QTextStream &QTextStream::operator>>(qulonglong &i)
2159 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(qulonglong);
2163 Reads a real number from the stream and stores it in \a f, then
2164 returns a reference to the QTextStream. The number is cast to
2165 the correct type. If no real number is detect on the stream, \a f
2168 As a special exception, QTextStream allows the strings "nan" and "inf" to
2169 represent NAN and INF floats or doubles.
2171 Leading whitespace is skipped.
2173 QTextStream &QTextStream::operator>>(float &f)
2175 IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(float);
2181 Stores the real number in the double \a f.
2183 QTextStream &QTextStream::operator>>(double &f)
2185 IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(double);
2189 Reads a word from the stream and stores it in \a str, then returns
2190 a reference to the stream. Words are separated by whitespace
2191 (i.e., all characters for which QChar::isSpace() returns true).
2193 Leading whitespace is skipped.
2195 QTextStream &QTextStream::operator>>(QString &str)
2198 CHECK_VALID_STREAM(*this);
2201 d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
2202 d->consumeLastToken();
2206 if (!d->scan(&ptr, &length, 0, QTextStreamPrivate::Space)) {
2207 setStatus(ReadPastEnd);
2211 str = QString(ptr, length);
2212 d->consumeLastToken();
2219 Converts the word to ISO-8859-1, then stores it in \a array.
2221 \sa QString::toLatin1()
2223 QTextStream &QTextStream::operator>>(QByteArray &array)
2226 CHECK_VALID_STREAM(*this);
2229 d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
2230 d->consumeLastToken();
2234 if (!d->scan(&ptr, &length, 0, QTextStreamPrivate::Space)) {
2235 setStatus(ReadPastEnd);
2239 for (int i = 0; i < length; ++i)
2240 array += ptr[i].toLatin1();
2242 d->consumeLastToken();
2249 Stores the word in \a c, terminated by a '\0' character. If no word is
2250 available, only the '\0' character is stored.
2252 Warning: Although convenient, this operator is dangerous and must
2253 be used with care. QTextStream assumes that \a c points to a
2254 buffer with enough space to hold the word. If the buffer is too
2255 small, your application may crash.
2257 If possible, use the QByteArray operator instead.
2259 QTextStream &QTextStream::operator>>(char *c)
2263 CHECK_VALID_STREAM(*this);
2264 d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
2265 d->consumeLastToken();
2269 if (!d->scan(&ptr, &length, 0, QTextStreamPrivate::Space)) {
2270 setStatus(ReadPastEnd);
2274 for (int i = 0; i < length; ++i)
2275 *c++ = ptr[i].toLatin1();
2277 d->consumeLastToken();
2283 void QTextStreamPrivate::putNumber(qulonglong number, bool negative)
2288 if (numberFlags & QTextStream::ShowBase)
2289 flags |= QLocalePrivate::ShowBase;
2290 if (numberFlags & QTextStream::ForceSign)
2291 flags |= QLocalePrivate::AlwaysShowSign;
2292 if (numberFlags & QTextStream::UppercaseBase)
2293 flags |= QLocalePrivate::UppercaseBase;
2294 if (numberFlags & QTextStream::UppercaseDigits)
2295 flags |= QLocalePrivate::CapitalEorX;
2297 // add thousands group separators. For backward compatibility we
2298 // don't add a group separator for C locale.
2299 if (locale != QLocale::c())
2300 flags |= QLocalePrivate::ThousandsGroup;
2302 const QLocalePrivate *dd = locale.d();
2303 int base = integerBase ? integerBase : 10;
2304 if (negative && base == 10) {
2305 result = dd->longLongToString(-static_cast<qlonglong>(number), -1,
2307 } else if (negative) {
2308 // Workaround for backward compatibility for writing negative
2309 // numbers in octal and hex:
2310 // QTextStream(result) << showbase << hex << -1 << oct << -1
2311 // should output: -0x1 -0b1
2312 result = dd->unsLongLongToString(number, -1, base, -1, flags);
2313 result.prepend(locale.negativeSign());
2315 result = dd->unsLongLongToString(number, -1, base, -1, flags);
2316 // workaround for backward compatibility - in octal form with
2317 // ShowBase flag set zero should be written as '00'
2318 if (number == 0 && base == 8 && numberFlags & QTextStream::ShowBase
2319 && result == QLatin1String("0")) {
2320 result.prepend(QLatin1Char('0'));
2323 putString(result, true);
2327 Writes the character \a c to the stream, then returns a reference
2332 QTextStream &QTextStream::operator<<(QChar c)
2335 CHECK_VALID_STREAM(*this);
2336 d->putString(QString(c));
2343 Converts \a c from ASCII to a QChar, then writes it to the stream.
2345 QTextStream &QTextStream::operator<<(char c)
2348 CHECK_VALID_STREAM(*this);
2349 d->putString(QString(QChar::fromAscii(c)));
2354 Writes the integer number \a i to the stream, then returns a
2355 reference to the QTextStream. By default, the number is stored in
2356 decimal form, but you can also set the base by calling
2359 \sa setFieldWidth(), setNumberFlags()
2361 QTextStream &QTextStream::operator<<(signed short i)
2364 CHECK_VALID_STREAM(*this);
2365 d->putNumber((qulonglong)qAbs(qlonglong(i)), i < 0);
2372 Writes the unsigned short \a i to the stream.
2374 QTextStream &QTextStream::operator<<(unsigned short i)
2377 CHECK_VALID_STREAM(*this);
2378 d->putNumber((qulonglong)i, false);
2385 Writes the signed int \a i to the stream.
2387 QTextStream &QTextStream::operator<<(signed int i)
2390 CHECK_VALID_STREAM(*this);
2391 d->putNumber((qulonglong)qAbs(qlonglong(i)), i < 0);
2398 Writes the unsigned int \a i to the stream.
2400 QTextStream &QTextStream::operator<<(unsigned int i)
2403 CHECK_VALID_STREAM(*this);
2404 d->putNumber((qulonglong)i, false);
2411 Writes the signed long \a i to the stream.
2413 QTextStream &QTextStream::operator<<(signed long i)
2416 CHECK_VALID_STREAM(*this);
2417 d->putNumber((qulonglong)qAbs(qlonglong(i)), i < 0);
2424 Writes the unsigned long \a i to the stream.
2426 QTextStream &QTextStream::operator<<(unsigned long i)
2429 CHECK_VALID_STREAM(*this);
2430 d->putNumber((qulonglong)i, false);
2437 Writes the qlonglong \a i to the stream.
2439 QTextStream &QTextStream::operator<<(qlonglong i)
2442 CHECK_VALID_STREAM(*this);
2443 d->putNumber((qulonglong)qAbs(i), i < 0);
2450 Writes the qulonglong \a i to the stream.
2452 QTextStream &QTextStream::operator<<(qulonglong i)
2455 CHECK_VALID_STREAM(*this);
2456 d->putNumber(i, false);
2461 Writes the real number \a f to the stream, then returns a
2462 reference to the QTextStream. By default, QTextStream stores it
2463 using SmartNotation, with up to 6 digits of precision. You can
2464 change the textual representation QTextStream will use for real
2465 numbers by calling setRealNumberNotation(),
2466 setRealNumberPrecision() and setNumberFlags().
2468 \sa setFieldWidth(), setRealNumberNotation(),
2469 setRealNumberPrecision(), setNumberFlags()
2471 QTextStream &QTextStream::operator<<(float f)
2473 return *this << double(f);
2479 Writes the double \a f to the stream.
2481 QTextStream &QTextStream::operator<<(double f)
2484 CHECK_VALID_STREAM(*this);
2486 QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
2487 switch (realNumberNotation()) {
2489 form = QLocalePrivate::DFDecimal;
2491 case ScientificNotation:
2492 form = QLocalePrivate::DFExponent;
2495 form = QLocalePrivate::DFSignificantDigits;
2500 if (numberFlags() & ShowBase)
2501 flags |= QLocalePrivate::ShowBase;
2502 if (numberFlags() & ForceSign)
2503 flags |= QLocalePrivate::AlwaysShowSign;
2504 if (numberFlags() & UppercaseBase)
2505 flags |= QLocalePrivate::UppercaseBase;
2506 if (numberFlags() & UppercaseDigits)
2507 flags |= QLocalePrivate::CapitalEorX;
2508 if (numberFlags() & ForcePoint)
2509 flags |= QLocalePrivate::Alternate;
2511 const QLocalePrivate *dd = d->locale.d();
2512 QString num = dd->doubleToString(f, d->realNumberPrecision, form, -1, flags);
2513 d->putString(num, true);
2518 Writes the string \a string to the stream, and returns a reference
2519 to the QTextStream. The string is first encoded using the assigned
2520 codec (the default codec is QTextCodec::codecForLocale()) before
2521 it is written to the stream.
2523 \sa setFieldWidth(), setCodec()
2525 QTextStream &QTextStream::operator<<(const QString &string)
2528 CHECK_VALID_STREAM(*this);
2529 d->putString(string);
2536 Writes \a string to the stream, and returns a reference to the
2537 QTextStream. The contents of \a string are converted with the
2538 QString constructor that takes a QLatin1String as argument.
2540 QTextStream &QTextStream::operator<<(const QLatin1String &string)
2543 CHECK_VALID_STREAM(*this);
2544 d->putString(QString(string));
2551 Writes \a array to the stream. The contents of \a array are
2552 converted with QString::fromAscii().
2554 QTextStream &QTextStream::operator<<(const QByteArray &array)
2557 CHECK_VALID_STREAM(*this);
2558 d->putString(QString::fromAscii(array.constData(), array.length()));
2565 Writes the constant string pointed to by \a string to the stream. \a
2566 string is assumed to be in ISO-8859-1 encoding. This operator
2567 is convenient when working with constant string data. Example:
2569 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 8
2571 Warning: QTextStream assumes that \a string points to a string of
2572 text, terminated by a '\0' character. If there is no terminating
2573 '\0' character, your application may crash.
2575 QTextStream &QTextStream::operator<<(const char *string)
2578 CHECK_VALID_STREAM(*this);
2579 d->putString(QLatin1String(string));
2586 Writes \a ptr to the stream as a hexadecimal number with a base.
2589 QTextStream &QTextStream::operator<<(const void *ptr)
2592 CHECK_VALID_STREAM(*this);
2593 int oldBase = d->integerBase;
2594 NumberFlags oldFlags = d->numberFlags;
2595 d->integerBase = 16;
2596 d->numberFlags |= ShowBase;
2597 d->putNumber(reinterpret_cast<quintptr>(ptr), false);
2598 d->integerBase = oldBase;
2599 d->numberFlags = oldFlags;
2604 \relates QTextStream
2606 Calls QTextStream::setIntegerBase(2) on \a stream and returns \a
2609 \sa oct(), dec(), hex(), {QTextStream manipulators}
2611 QTextStream &bin(QTextStream &stream)
2613 stream.setIntegerBase(2);
2618 \relates QTextStream
2620 Calls QTextStream::setIntegerBase(8) on \a stream and returns \a
2623 \sa bin(), dec(), hex(), {QTextStream manipulators}
2625 QTextStream &oct(QTextStream &stream)
2627 stream.setIntegerBase(8);
2632 \relates QTextStream
2634 Calls QTextStream::setIntegerBase(10) on \a stream and returns \a
2637 \sa bin(), oct(), hex(), {QTextStream manipulators}
2639 QTextStream &dec(QTextStream &stream)
2641 stream.setIntegerBase(10);
2646 \relates QTextStream
2648 Calls QTextStream::setIntegerBase(16) on \a stream and returns \a
2651 \note The hex modifier can only be used for writing to streams.
2652 \sa bin(), oct(), dec(), {QTextStream manipulators}
2654 QTextStream &hex(QTextStream &stream)
2656 stream.setIntegerBase(16);
2661 \relates QTextStream
2663 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2664 QTextStream::ShowBase) on \a stream and returns \a stream.
2666 \sa noshowbase(), forcesign(), forcepoint(), {QTextStream manipulators}
2668 QTextStream &showbase(QTextStream &stream)
2670 stream.setNumberFlags(stream.numberFlags() | QTextStream::ShowBase);
2675 \relates QTextStream
2677 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2678 QTextStream::ForceSign) on \a stream and returns \a stream.
2680 \sa noforcesign(), forcepoint(), showbase(), {QTextStream manipulators}
2682 QTextStream &forcesign(QTextStream &stream)
2684 stream.setNumberFlags(stream.numberFlags() | QTextStream::ForceSign);
2689 \relates QTextStream
2691 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2692 QTextStream::ForcePoint) on \a stream and returns \a stream.
2694 \sa noforcepoint(), forcesign(), showbase(), {QTextStream manipulators}
2696 QTextStream &forcepoint(QTextStream &stream)
2698 stream.setNumberFlags(stream.numberFlags() | QTextStream::ForcePoint);
2703 \relates QTextStream
2705 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2706 ~QTextStream::ShowBase) on \a stream and returns \a stream.
2708 \sa showbase(), noforcesign(), noforcepoint(), {QTextStream manipulators}
2710 QTextStream &noshowbase(QTextStream &stream)
2712 stream.setNumberFlags(stream.numberFlags() &= ~QTextStream::ShowBase);
2717 \relates QTextStream
2719 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2720 ~QTextStream::ForceSign) on \a stream and returns \a stream.
2722 \sa forcesign(), noforcepoint(), noshowbase(), {QTextStream manipulators}
2724 QTextStream &noforcesign(QTextStream &stream)
2726 stream.setNumberFlags(stream.numberFlags() &= ~QTextStream::ForceSign);
2731 \relates QTextStream
2733 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2734 ~QTextStream::ForcePoint) on \a stream and returns \a stream.
2736 \sa forcepoint(), noforcesign(), noshowbase(), {QTextStream manipulators}
2738 QTextStream &noforcepoint(QTextStream &stream)
2740 stream.setNumberFlags(stream.numberFlags() &= ~QTextStream::ForcePoint);
2745 \relates QTextStream
2747 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2748 QTextStream::UppercaseBase) on \a stream and returns \a stream.
2750 \sa lowercasebase(), uppercasedigits(), {QTextStream manipulators}
2752 QTextStream &uppercasebase(QTextStream &stream)
2754 stream.setNumberFlags(stream.numberFlags() | QTextStream::UppercaseBase);
2759 \relates QTextStream
2761 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2762 QTextStream::UppercaseDigits) on \a stream and returns \a stream.
2764 \sa lowercasedigits(), uppercasebase(), {QTextStream manipulators}
2766 QTextStream &uppercasedigits(QTextStream &stream)
2768 stream.setNumberFlags(stream.numberFlags() | QTextStream::UppercaseDigits);
2773 \relates QTextStream
2775 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2776 ~QTextStream::UppercaseBase) on \a stream and returns \a stream.
2778 \sa uppercasebase(), lowercasedigits(), {QTextStream manipulators}
2780 QTextStream &lowercasebase(QTextStream &stream)
2782 stream.setNumberFlags(stream.numberFlags() & ~QTextStream::UppercaseBase);
2787 \relates QTextStream
2789 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2790 ~QTextStream::UppercaseDigits) on \a stream and returns \a stream.
2792 \sa uppercasedigits(), lowercasebase(), {QTextStream manipulators}
2794 QTextStream &lowercasedigits(QTextStream &stream)
2796 stream.setNumberFlags(stream.numberFlags() & ~QTextStream::UppercaseDigits);
2801 \relates QTextStream
2803 Calls QTextStream::setRealNumberNotation(QTextStream::FixedNotation)
2804 on \a stream and returns \a stream.
2806 \sa scientific(), {QTextStream manipulators}
2808 QTextStream &fixed(QTextStream &stream)
2810 stream.setRealNumberNotation(QTextStream::FixedNotation);
2815 \relates QTextStream
2817 Calls QTextStream::setRealNumberNotation(QTextStream::ScientificNotation)
2818 on \a stream and returns \a stream.
2820 \sa fixed(), {QTextStream manipulators}
2822 QTextStream &scientific(QTextStream &stream)
2824 stream.setRealNumberNotation(QTextStream::ScientificNotation);
2829 \relates QTextStream
2831 Calls QTextStream::setFieldAlignment(QTextStream::AlignLeft)
2832 on \a stream and returns \a stream.
2834 \sa right(), center(), {QTextStream manipulators}
2836 QTextStream &left(QTextStream &stream)
2838 stream.setFieldAlignment(QTextStream::AlignLeft);
2843 \relates QTextStream
2845 Calls QTextStream::setFieldAlignment(QTextStream::AlignRight)
2846 on \a stream and returns \a stream.
2848 \sa left(), center(), {QTextStream manipulators}
2850 QTextStream &right(QTextStream &stream)
2852 stream.setFieldAlignment(QTextStream::AlignRight);
2857 \relates QTextStream
2859 Calls QTextStream::setFieldAlignment(QTextStream::AlignCenter)
2860 on \a stream and returns \a stream.
2862 \sa left(), right(), {QTextStream manipulators}
2864 QTextStream ¢er(QTextStream &stream)
2866 stream.setFieldAlignment(QTextStream::AlignCenter);
2871 \relates QTextStream
2873 Writes '\n' to the \a stream and flushes the stream.
2877 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 9
2879 Note: On Windows, all '\n' characters are written as '\r\n' if
2880 QTextStream's device or string is opened using the QIODevice::Text flag.
2882 \sa flush(), reset(), {QTextStream manipulators}
2884 QTextStream &endl(QTextStream &stream)
2886 return stream << QLatin1Char('\n') << flush;
2890 \relates QTextStream
2892 Calls QTextStream::flush() on \a stream and returns \a stream.
2894 \sa endl(), reset(), {QTextStream manipulators}
2896 QTextStream &flush(QTextStream &stream)
2903 \relates QTextStream
2905 Calls QTextStream::reset() on \a stream and returns \a stream.
2907 \sa flush(), {QTextStream manipulators}
2909 QTextStream &reset(QTextStream &stream)
2916 \relates QTextStream
2918 Calls skipWhiteSpace() on \a stream and returns \a stream.
2920 \sa {QTextStream manipulators}
2922 QTextStream &ws(QTextStream &stream)
2924 stream.skipWhiteSpace();
2929 \fn QTextStreamManipulator qSetFieldWidth(int width)
2930 \relates QTextStream
2932 Equivalent to QTextStream::setFieldWidth(\a width).
2936 \fn QTextStreamManipulator qSetPadChar(QChar ch)
2937 \relates QTextStream
2939 Equivalent to QTextStream::setPadChar(\a ch).
2943 \fn QTextStreamManipulator qSetRealNumberPrecision(int precision)
2944 \relates QTextStream
2946 Equivalent to QTextStream::setRealNumberPrecision(\a precision).
2949 #ifndef QT_NO_TEXTCODEC
2951 \relates QTextStream
2953 Toggles insertion of the Byte Order Mark on \a stream when QTextStream is
2954 used with a UTF codec.
2956 \sa QTextStream::setGenerateByteOrderMark(), {QTextStream manipulators}
2958 QTextStream &bom(QTextStream &stream)
2960 stream.setGenerateByteOrderMark(true);
2965 Sets the codec for this stream to \a codec. The codec is used for
2966 decoding any data that is read from the assigned device, and for
2967 encoding any data that is written. By default,
2968 QTextCodec::codecForLocale() is used, and automatic unicode
2969 detection is enabled.
2971 If QTextStream operates on a string, this function does nothing.
2973 \warning If you call this function while the text stream is reading
2974 from an open sequential socket, the internal buffer may still contain
2975 text decoded using the old codec.
2977 \sa codec(), setAutoDetectUnicode(), setLocale()
2979 void QTextStream::setCodec(QTextCodec *codec)
2982 qint64 seekPos = -1;
2983 if (!d->readBuffer.isEmpty()) {
2984 if (!d->device->isSequential()) {
2989 if (seekPos >=0 && !d->readBuffer.isEmpty())
2994 Sets the codec for this stream to the QTextCodec for the encoding
2995 specified by \a codecName. Common values for \c codecName include
2996 "ISO 8859-1", "UTF-8", and "UTF-16". If the encoding isn't
2997 recognized, nothing happens.
3001 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 10
3003 \sa QTextCodec::codecForName(), setLocale()
3005 void QTextStream::setCodec(const char *codecName)
3007 QTextCodec *codec = QTextCodec::codecForName(codecName);
3013 Returns the codec that is current assigned to the stream.
3015 \sa setCodec(), setAutoDetectUnicode(), locale()
3017 QTextCodec *QTextStream::codec() const
3019 Q_D(const QTextStream);
3024 If \a enabled is true, QTextStream will attempt to detect Unicode
3025 encoding by peeking into the stream data to see if it can find the
3026 UTF-16 or UTF-32 BOM (Byte Order Mark). If this mark is found, QTextStream
3027 will replace the current codec with the UTF codec.
3029 This function can be used together with setCodec(). It is common
3030 to set the codec to UTF-8, and then enable UTF-16 detection.
3032 \sa autoDetectUnicode(), setCodec()
3034 void QTextStream::setAutoDetectUnicode(bool enabled)
3037 d->autoDetectUnicode = enabled;
3041 Returns true if automatic Unicode detection is enabled, otherwise
3042 returns false. Automatic Unicode detection is enabled by default.
3044 \sa setAutoDetectUnicode(), setCodec()
3046 bool QTextStream::autoDetectUnicode() const
3048 Q_D(const QTextStream);
3049 return d->autoDetectUnicode;
3053 If \a generate is true and a UTF codec is used, QTextStream will insert
3054 the BOM (Byte Order Mark) before any data has been written to the
3055 device. If \a generate is false, no BOM will be inserted. This function
3056 must be called before any data is written. Otherwise, it does nothing.
3058 \sa generateByteOrderMark(), bom()
3060 void QTextStream::setGenerateByteOrderMark(bool generate)
3063 if (d->writeBuffer.isEmpty()) {
3065 d->writeConverterState.flags &= ~QTextCodec::IgnoreHeader;
3067 d->writeConverterState.flags |= QTextCodec::IgnoreHeader;
3072 Returns true if QTextStream is set to generate the UTF BOM (Byte Order
3073 Mark) when using a UTF codec; otherwise returns false. UTF BOM generation is
3074 set to false by default.
3076 \sa setGenerateByteOrderMark()
3078 bool QTextStream::generateByteOrderMark() const
3080 Q_D(const QTextStream);
3081 return (d->writeConverterState.flags & QTextCodec::IgnoreHeader) == 0;
3089 Sets the locale for this stream to \a locale. The specified locale is
3090 used for conversions between numbers and their string representations.
3092 The default locale is C and it is a special case - the thousands
3093 group separator is not used for backward compatibility reasons.
3097 void QTextStream::setLocale(const QLocale &locale)
3106 Returns the locale for this stream. The default locale is C.
3110 QLocale QTextStream::locale() const
3112 Q_D(const QTextStream);
3118 #ifndef QT_NO_QOBJECT
3119 #include "qtextstream.moc"