Qtのコンソールアプリのソースコードをビルドしてみます。
ソースコード
ファイルメイン:main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QTextStream>
void printArguments(const QCoreApplication &app)
{
qInfo() << "=== Command line arguments ===";
const QStringList args = app.arguments();
for (int i = 0; i < args.size(); ++i) {
qInfo() << i << ":" << args[i];
}
qInfo() << "";
}
void listFiles(const QString &path)
{
qInfo() << "=== File list of:" << path << "===";
QDir dir(path);
if (!dir.exists()) {
qWarning() << "Directory not found:" << path;
return;
}
const QFileInfoList list = dir.entryInfoList(
QDir::Files | QDir::NoDotAndDotDot | QDir::Readable,
QDir::Name
);
for (const QFileInfo &fi : list) {
qInfo().noquote() << fi.fileName();
}
qInfo() << "";
}
void printTextFile(const QString &filepath)
{
qInfo() << "=== Read text file:" << filepath << "===";
QFile file(filepath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qWarning() << "Failed to open:" << filepath;
return;
}
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
qInfo().noquote() << line;
}
qInfo() << "";
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
printArguments(app);
// 例: カレントディレクトリのファイル一覧
listFiles(".");
// 例: コマンドライン引数にファイルパスがあればそれを読む
if (app.arguments().size() > 1) {
printTextFile(app.arguments().at(1));
} else {
qInfo() << "Usage: app <textfile>";
}
return 0;
}
ビルドコマンド例
g++ main.cpp `
-IC:\Users\karet\scoop\apps\msys2\current\ucrt64\include\qt6 `
-IC:\Users\karet\scoop\apps\msys2\current\ucrt64\include\qt6\QtCore `
-LC:\Users\karet\scoop\apps\msys2\current\ucrt64\lib `
-lQt6Core `
-o app.exe
実行例
コマンドライン引数なし:
PS J:\qtcpp\05_console> .\app.exe
=== Command line arguments ===
0 : "J:\\qtcpp\\05_console\\app.exe"
=== File list of: "." ===
app.exe
main.cpp
Usage: app <textfile>
ファイルのパスを指定:
.\app.exe .\sample.txt
=== Command line arguments ===
0 : "J:\\qtcpp\\05_console\\app.exe"
1 : ".\\sample.txt"
=== File list of: "." ===
app.exe
main.cpp
sample.txt
=== Read text file: ".\\sample.txt" ===
サンプル
感想
非常に自然なサンプルコードで、自分が知っている昔のC++とはまるで別物のように感じました。
Qt のクラスを使うことで、C++ の低レイヤー感が薄まり、まるでモダン言語のような書き方ができます。
今回使用した Qt の主な機能は以下の通りです。
QString… 文字列クラスQInfo… 標準出力へのログQWarning… 標準エラーへのログQDir… ディレクトリ操作(一覧取得・存在確認など)QFile… ファイルの存在確認、読み書きQTextStream… テキストファイルの読み書き用ストリーム
C++ の標準ライブラリを直接使うのではなく、Qt の API を用いることで OS の違いを気にせずに書ける点が非常に大きなメリットです。
そのおかげで、C++ があたかも今風の “普通のモダンなプログラミング言語” のように見えてきます。

コメント