Qt I/O Class Overview
Qt provides two core classes for input/output operations:
- QTextStream: Handles text-based read/write operations on QString, QIODevice, or QByteArray objects
- QDataStream: Performs binary format read/write operations exclusively on QIODevice or QByteArray
QIODevice Fundamentals
QIODevice serves as the base interface for all I/O devices, offering read/write functionality. Devices are categorized as:
- Random Access: Support position seeking (QFile, QTemporaryFile, QBuffer)
- Sequential: No random access (QProcess, QTcpSocket, QUdpSocket)
QBuffer provides a QIODevice interface for QByteArray access.
Binary Data Handling with QDataStream
QDataStream serializes objects into binary format for storage or transmission. Key considerations:
- Endianness:
- Big-Endian (default): Most significant byte first
- Little-Endian: Least significant byte first
- Serialization: Converts object state to storable/transmittable binary format
Supported types include fundamental C++ types, Qt types (QBrush, QDateTime, etc.), and containers (QList, QMap). Usage pattern:
QFile dataFile("records.bin");
if (dataFile.open(QIODevice::WriteOnly)) {
QDataStream output(&dataFile);
output << dataset;
}
Text Processing with QTextStream
Character Encoding Fundamentals
- Character sets map characters to numeric values (ASCII, Unicode)
- Encoding schemes translate values to binary (UTF-8, UTF-16)
- BOM (Byte Order Mark) indicates encoding format and endianness
QTextStream Operations
Features include:
- Automatic encoding conversion using QTextCodec
- Platform-specific newline handling
- Three reading approaches:
- Line-by-line (readLine())
- Word-by-word (>> operator)
- Character-by-character
Formatting example:
QTextStream console(stdout);
console.setIntegerBase(16);
console << "Hex value: " << 255;
Core Functions
- flush(): Writes buffered data to device
- readLine(): Retrieves text line without newline characters
- seek(): Positions within the stream
- skipWhiteSpace(): Ignores whitespace characters
File reading implementation:
#include <QCoreApplication>
#include <QFile>
#include <QTextStream>
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
QFile logFile("access.log");
if (!logFile.open(QIODevice::ReadOnly | QIODevice::Text))
return 1;
QTextStream logStream(&logFile);
while (!logStream.atEnd()) {
QString record = logStream.readLine();
qDebug() << record;
}
return 0;
}