dev/qt/ PoorMansGrepV1
This is the most trivial example of a grep
I could write using Qt. All it does is read line by line, apply a QRegularExpression
and prints any matching line.
#include <QCoreApplication>
#include <QFile>
#include <QRegularExpression>
#include <QDir>
// args are:
// pattern file1 [file2 ...]
// if file1 not specified, use stdin
QTextStream& qStdOut()
{
static QTextStream ts( stdout );
return ts;
}
QTextStream& qStdErr()
{
static QTextStream ts( stderr );
return ts;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QDir dir;
qStdOut() << dir.currentPath() << "\n";
qStdOut().flush();
if( argc < 3 )
{
qStdOut() << "pmgrep <pattern> <files...>\n";
qStdOut().flush();
}
else
{
// take pattern from argv[1]
// iterate over args from 2 onwards
const char* pattern = argv[1];
const QRegularExpression regular_expression(pattern);
for(int i=2; i<argc; i++)
{
const char* filename = argv[i];
// open file argv[i]
QFile inputFile(filename);
if (inputFile.open(QIODevice::ReadOnly))
{
QTextStream in(&inputFile);
while (!in.atEnd())
{
QString line = in.readLine();
const QRegularExpressionMatch match = regular_expression.match(line);
if( match.hasMatch() )
{
qStdOut() << line << "\n";
}
qStdOut().flush();
}
inputFile.close();
} else {
// print to stderr
qStdErr() << "Failed to open file: " << filename << "\n";
}
}
}
}