c++统计文件行数

由于申请软件著作权的时候,需要统计代码的行数,然后自己就写了一个,分享给大家。

// 获取文件的行数
//filepath:文件路径
//ruleData:一些配置信息,bCountNullLine:是否统计空行
int getFileLine(string filePath, const RuleData& ruleData){
	int nLines = 0;
	ifstream ReadFile;
	int n = 0;
	string tmp;
	ReadFile.open(filePath, ios::in);//ios::in 表示以只读的方式读取文件
	if (ReadFile.fail())//文件打开失败:返回0
		return 0;
	else//文件存在
	{
		while (getline(ReadFile, tmp))
		{
			if (!ruleData.bCountNullLine && tmp == "")
				continue;	//不统计空行

			n++;
		}
	}
	ReadFile.close();
	return n;
}

// 获取文件夹下的所有文件行数
//dirPath:总文件夹的路径
//secDirPath:次文件夹路径
//mapFileExt:文件后缀列表
//ruleData:一些配置信息
int countDirTotalLines(const string& dirPath, string secDirPath, const std::map<string, bool>& mapFileExt, const RuleData& ruleData){
	int nTotalLines = 0;

	long hFile = 0;
	struct _finddata_t fileInfo;
	std::string pathName, exdName;
	string folderPath = dirPath + secDirPath;
	if ((hFile = _findfirst(pathName.assign(folderPath).append("\\*").c_str(), &fileInfo)) == -1) {
		return nTotalLines;
	}
	do {
		const std::string filename = fileInfo.name;
		if (filename == "." || filename == "..")
			continue;

		string secDirPath2 = secDirPath + "/" + filename;
		if (fileInfo.attrib&_A_SUBDIR)	//文件夹-
		{
			int nLines = countDirTotalLines(dirPath, secDirPath2, mapFileExt, ruleData);
			nTotalLines += nLines;
			printf("%s总行数:%d\n", secDirPath2.c_str(), nLines);
		}
		else{
			const std::string& filepath = folderPath + "/" + filename;
			string fileExt = getFileExt(filename);
			if (mapFileExt.count(fileExt) > 0)
			{
				int nLines = getFileLine(filepath, ruleData);
				nTotalLines += nLines;
				printf("%s/%s行数:%d\n", secDirPath2.c_str(), filename.c_str(), nLines);
			}
		}

	} while (_findnext(hFile, &fileInfo) == 0);
	_findclose(hFile);
	return nTotalLines;
}

csdn源工程下载链接
github地址

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值