统计某个目录下代码行数
2024-01-08 本文已影响0人
豪爵吸金ing
写了个控制台程序,可以统计某个目录下,Qt项目的C++代码行数
#include <QDebug>
#include <QCoreApplication>
#include <QDir>
#include <QFileInfoList>
#include <QFile>
#include <QTextStream>
int countLines(const QString& filePath) {
if(filePath.contains("moc_") || filePath.contains("ui_"))
return 0;
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return 0;
QTextStream in(&file);
int lineCount = 0;
while (!in.atEnd()) {
QString line = in.readLine();
if (!line.trimmed().isEmpty()) // 忽略空行
lineCount++;
}
return lineCount;
}
void processDirectory(const QDir& directory, int& totalLines) {
QFileInfoList fileList = directory.entryInfoList(QStringList() << "*.cpp" << "*.h", QDir::Files);
foreach (const QFileInfo& fileInfo, fileList) {
int lines = countLines(fileInfo.filePath());
totalLines += lines;
qDebug() << fileInfo.fileName() << ": " << lines;
}
QFileInfoList subDirList = directory.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
foreach (const QFileInfo& subDirInfo, subDirList) {
QDir subDir(subDirInfo.filePath());
processDirectory(subDir, totalLines);
}
}
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
QString directoryPath = "D:/truck/XXX"; // 替换为你要统计的目录路径
QDir directory(directoryPath);
int totalLines = 0;
processDirectory(directory, totalLines);
qDebug() << "Total lines: " << totalLines;
return a.exec();
}