QTextStream

QTextStream 像是一個適配器,能支持多數據源

#include <QTextStream >
#include <QString >
#include <QFile >

QTextStream cout(stdout, QIODevice::WriteOnly);
QTextStream cerr(stderr, QIODevice::WriteOnly);

int main() {
QString str, newstr;

QTextStream strbuf(&str); //使用QString做數據源

int lucky = 7;
float pi = 3.14;
double e = 2.71;

cout << "An in-memory stream" << endl;
strbuf << "luckynumber: " << lucky << endl
<< "pi: " << pi << endl
<< "e: " << e << endl;

cout << str;

QFile data("mydata");
data.open(QIODevice::WriteOnly);
QTextStream out(&data); //使用QDevice做數據源
out << str ;
data.close();

cout << "Read data from the file - watch for errors." << endl;
if(data.open(QIODevice::ReadOnly)) { /*Make sure the file exists before
attempting to read.*/
QTextStream in(&data);
int lucky2;
in >> newstr >> lucky2;
if (lucky != lucky2)
cerr << "ERROR! wrong " << newstr << lucky2 << endl;
else
cout << newstr << " OK" << endl;

float pi2;
in >> newstr >> pi2;
if (pi2 != pi)
cerr << "ERROR! Wrong " << newstr << pi2 << endl;
else
cout << newstr << " OK" << endl;

double e2;
in >> newstr >> e2;
if (e2 != e)
cerr << "ERROR: Wrong " << newstr << e2 << endl;
else
cout << newstr << " OK" << endl;
data.close();
}

cout << "Read from file line-by-line" << endl;
if(data.open(QIODevice::ReadOnly)) {
QTextStream in(&data);
while (not in.atEnd()) {
newstr = in.readLine();
cout << newstr << endl;
}
data.close();
}
return 0;
}

評註:從上面的例子可以看出,QTextStream不負責文件的打開與創建,僅僅提供文件訪問的方法,實現了功能的獨立性
,由於它支持多數據,不區分讀寫的方向,比fstream流使用起來更加方便

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章