代碼在GitHubMaolinYe/CodeCounter: C++20實現的代碼統計器,代碼量小于100行,可以統計目錄下所有代碼文件的行數 (github.com)
前段時間到處面試找實習,有技術負責人的負責人問我C++寫過多少行,5萬還是10萬,用來評估熟練度,有點難頂,于是寫個代碼統計器吧,輸入文件夾目錄或者代碼文件,可以統計所有代碼的行數
可以直接編譯代碼運行程序,在控制臺輸入目錄的路徑按下回車即可,例如輸入
C:\Users\Yezi\Desktop\C++\CodeCounter
也可以在終端命令行直接運行編譯好的程序,帶上參數運行,例如輸入
.\CodeCounter.exe C:\Users\Yezi\Desktop\C++\CodeCounter
思路比較簡單,主要是用到了C++17的filesystem庫用來解析目錄和提取文件后綴,如果路徑是個目錄就提取子目錄項逐個分析,如果子目錄項是目錄就遞歸調用本身繼續解析目錄,如果是代碼文件就開始計數行數
//
// Created by YEZI on 2024/5/20.
//#ifndef CODECOUNTER_H
#define CODECOUNTER_H
#include<vector>
#include<string>
#include<filesystem>
#include <fstream>
#include <iostream>class CodeCounter {int lines = 0;// 檢查是否是代碼文件static bool isCodeFile(const std::filesystem::path &path) {// 常見代碼文件后綴static const std::vector<std::string> extensions = {".cpp", ".h", ".java", ".py", ".cs", ".js", ".go", ".c", ".cc", ".hh"};// 檢查路徑是否存在if (std::filesystem::exists(path) == false) {std::cerr << "There is no file " << path << std::endl;return false;}// 檢查是否是文件if (is_regular_file(path) == false) {std::cerr << path << " is no a file." << std::endl;return false;}std::string extension = path.extension().string();for (const auto &e: extensions) {if (e == extension) {return true;}}return false;}void countCodeFile(const std::filesystem::path &filePath) {// 檢查是否是代碼文件if (isCodeFile(filePath) == false)return;std::ifstream file(filePath);// 檢查文件是否可以打開if (file.is_open() == false) {std::cerr << "Error opening file: " << filePath << std::endl;return;}std::string trash;int count=0;while (std::getline(file, trash)) {++count;}lines+=count;std::cout<<filePath<<" Lines: "<<count<<std::endl;}void countDirectory(const std::filesystem::path &path) {// 檢查是否是目錄if (is_directory(path) == false)return;for (const auto &entry: std::filesystem::directory_iterator(path)) {if (entry.is_directory())countDirectory(entry.path());elsecountCodeFile(entry.path());}}public:void countThis(const std::filesystem::path &path) {if (is_directory(path))countDirectory(path);elsecountCodeFile(path);std::cout << "Code Lines: " << lines;}
};
#endif //CODECOUNTER_H
從命令行參數讀取目錄或者從控制臺輸入讀取目錄
#include <iostream>
#include"CodeCounter.h"int main(int argc, char *argv[]) {CodeCounter code_counter;std::string path;if (argc == 2)path.assign(argv[1]);elsestd::getline(std::cin, path);code_counter.countThis(path);return 0;
}