分享

c++统计文件行数...

 wuxinit_ 2022-11-21 发布于湖北

由于申请软件著作权的时候,需要统计代码的行数,然后自己就写了一个,分享给大家。
// 获取文件的行数
//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博主「Reno_007」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/cwn0812/article/details/105836158/

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多