1.读文件
- QFile file("/home/administrator/testdir/test.txt");
- if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
- qDebug()<<"Can't open the file!"<<endl;
- }
- while(!file.atEnd()) {
- QByteArray line = file.readLine();
- QString str(line);
- qDebug()<< str;
- }
注意QByteArray与QString之间的转换
另一种用QTextStream的方式
- QFile f("c:\\test.txt");
- if(!f.open(QIODevice::ReadOnly | QIODevice::Text))
- {
- cout << "Open failed." << endl;
- return -1;
- }
-
- QTextStream txtInput(&f);
- QString lineStr;
- while(!txtInput.atEnd())
- {
- lineStr = txtInput.readLine();
- cout << lineStr << endl;
- }
-
- f.close();
2.写文件
- QFile f("c:\\test.txt");
- if(!f.open(QIODevice::WriteOnly | QIODevice::Text))
- {
- cout << "Open failed." << endl;
- return -1;
- }
-
- QTextStream txtOutput(&f);
- QString s1("123");
- quint32 n1(123);
-
- txtOutput << s1 << endl;
- txtOutput << n1 << endl;
-
- f.close();