QTextStream 的简单理解
文章目錄
- QTextStream 的簡單理解
- QTextStream類提供了使用QIODevice讀寫文本的基本功能。
- 還有一種通常的用法就是控制臺命令的讀寫
- 除了QTextStream的構造函數,還要常用的一些方法
- 通常有三種方式來讀文本文件
- Qt提供了幾個和iostream相似的全局函數:
QTextStream 的簡單理解
QTextStream類提供了使用QIODevice讀寫文本的基本功能。
QTextStream可以操作QIODevice上,支持QByteArray和QString。如果使用QTextStream的operators,可以方便的讀寫words,lines 和numbers. 對一般的文本,QTextStream支持格式化對齊,格式化數字 等。例如
QFile data(“output.txt”);
if (data.open(QFile::WriteOnly | QFile::Truncate)) {
QTextStream out(&data);
out << "Result: " << qSetFieldWidth(10) << left << 3.14 << 2.7;
// writes "Result: 3.14 2.7 "
}
還有一種通常的用法就是控制臺命令的讀寫
,例如:
QTextStream stream(stdin);
QString line;
while (stream.readLineInto(&line)) {
…
}
除了QTextStream的構造函數,還要常用的一些方法
,例如:
setDevice() : 設置設備
setString(): 設置字符串
seek():查找位置
atEnd():返回是否還有數據可讀
flush():清空寫緩存區
QTextStream 使用的是Unicode 緩存,Qt中的QTextCodec類 可以支持各種字符集。
通常有三種方式來讀文本文件
:
- chunk By chunk(塊讀):readLine()和readAll()
- Word By Word(按字讀):
- character By character(按字節讀):
Qt提供了幾個和iostream相似的全局函數:
?bin設置QTextStream來讀/寫二進制數字
-?oct設置QTextStream來讀/寫八進制數字
-?dec設置QTextStream來讀/寫十進制數字
-?hex設置QTextStream來讀/寫十六進制數字
-?endl強制換行
-?flush強制QIODevice刷新任何被緩存的數據
-?ws作為任何可用的控制符(在輸入的時候)
-?reset重新設置QTextStream為它的缺省模式(請見reset())
-?qSetW(int)設置字段寬度作為指定參數
-?qSetFill(int)設置填充字符作為指定參數
-?qSetPrecision(int)設置精確度作為指定參數
簡單示例:
include <QCoreApplication> #include <QFile> #include <QTextStream> #include <QDebug> #include <QStringList> int main(int argc, char *argv[]) {QCoreApplication a(argc, argv);//寫入文件QFile myFile("log.txt");if(!myFile.open(QIODevice::WriteOnly)){qDebug()<<myFile.errorString();}QTextStream textStream(&myFile);textStream<<"this is first line.\r\n";textStream<<"this is second line.\r\n";textStream<<"this is third line.\r\n";textStream.flush();myFile.close();//讀取文件if(!myFile.open(QIODevice::ReadOnly)){qDebug()<<myFile.errorString();}textStream.setDevice(&myFile);while(!textStream.atEnd()){QString str1 = textStream.readLine();//每次讀取一行qDebug()<<str1;}textStream.seek(0);QString strAll = textStream.readAll();//全部讀取qDebug()<<strAll;//每一次讀取一個單詞,過濾掉空格textStream.seek(0);while(!textStream.atEnd()){QString str;textStream>>str;qDebug()<<str;}//每一次讀取一個字節textStream.seek(0);while(!textStream.atEnd()){textStream.skipWhiteSpace();QString str = textStream.read(1);qDebug()<<str;}myFile.close();return a.exec(); }總結
以上是生活随笔為你收集整理的QTextStream 的简单理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有线同步--ASP007
- 下一篇: The IEEE 802.15.4 MA