国外怎么做网站,柯桥做网站,小程序搭建需要多久,河南房产网站建设代码在GitHubMaolinYe/CodeCounter: C20实现的代码统计器#xff0c;代码量小于100行#xff0c;可以统计目录下所有代码文件的行数 (github.com)
前段时间到处面试找实习#xff0c;有技术负责人的负责人问我C写过多少行#xff0c;5万还是10万#xff0c;用来评估熟练度…代码在GitHubMaolinYe/CodeCounter: C20实现的代码统计器代码量小于100行可以统计目录下所有代码文件的行数 (github.com)
前段时间到处面试找实习有技术负责人的负责人问我C写过多少行5万还是10万用来评估熟练度有点难顶于是写个代码统计器吧输入文件夹目录或者代码文件可以统计所有代码的行数
可以直接编译代码运行程序在控制台输入目录的路径按下回车即可例如输入
C:\Users\Yezi\Desktop\C\CodeCounter
也可以在终端命令行直接运行编译好的程序带上参数运行例如输入
.\CodeCounter.exe C:\Users\Yezi\Desktop\C\CodeCounter
思路比较简单主要是用到了C17的filesystem库用来解析目录和提取文件后缀如果路径是个目录就提取子目录项逐个分析如果子目录项是目录就递归调用本身继续解析目录如果是代码文件就开始计数行数
//
// Created by YEZI on 2024/5/20.
//#ifndef CODECOUNTER_H
#define CODECOUNTER_H
#includevector
#includestring
#includefilesystem
#include fstream
#include iostreamclass CodeCounter {int lines 0;// 检查是否是代码文件static bool isCodeFile(const std::filesystem::path path) {// 常见代码文件后缀static const std::vectorstd::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 count0;while (std::getline(file, trash)) {count;}linescount;std::coutfilePath Lines: countstd::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
#includeCodeCounter.hint 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;
}