Qt4でファイル読み込み
#include <QFile>
#include <QTextStream>
#include <iostream>
int main( int argc, char* argv[] )
{
QFile file( "file.txt" );
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
std::cout << "can not open file." << std::endl;
return 0;
}
int n = 0;
QTextStream in( &file );
while (!in.atEnd()) {
QString line = in.readLine();
std::cout << n << " : " << line.toStdString() << std::endl;
n++;
}
return 0;
}
- file.txt
aaa bbb ccc あああ いいい ううう zzz
- 実行結果
0 : aaa
1 : bbb
2 : ccc
3 :
4 :
5 :
6 : zzz
1 : bbb
2 : ccc
3 :
4 :
5 :
6 : zzz
ファイル・ビュー(GUI)
画面イメージ

ソース

MainForm.ui | Designerで作成 |
MainForm.h | |
MainForm.cpp | |
main.cpp |
- MainForm.cppの表示関数抜粋
void MainForm::slot_textView()
{
QString fileName;
fileName = fileNameLine->text();
std::cout << "file: " << fileName.toStdString() << std::endl;
QFile file( fileName );
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
viewText->clear();
QTextStream in( &file );
while (!in.atEnd()) {
QString line = in.readLine();
// テキスト追加
viewText->append( line );
}
}
else {
std::cout << "can not open file." << std::endl;
}
}
コンパイル&実行
$ qmake -project $ qmake $ make $ ./ReadFile_gui