闲来无事,化了点时间,写了这个代码量检测,比较简陋,实现了大概的功能,循环遍历一个盘符下的所有文件,找出.cpp(或者别的),然后打开文件,看有多少行数,数据结构用的是栈,并没有用递归算法,怕文件埋得太深,导致效率太低,以前看到说递归7次以上 效率会很差,有待求证,贴上代码
/*
Author:chao
Time:2010-5-16
compiler:gcc
os:xp
*/
#include <cstdlib>
#include <iostream>
#include<stack>
#include<string>
#include<fstream>
#include<exception>
#include<algorithm>
#include"dir.h"
#define ISRIGHT 1
using namespace std;
string panfu="E:";//在这里改 初始位置
string xiegang="//";
string filegeshi2="*.*";
string filetype=".cpp";// 这里可以修改需要查找的类型
int hangshu=0; //行数
int countsofhangshu(string filename){
const char *fn=filename.c_str();//stirng ->const char*
fstream infile(fn);
int ret=0;
if(infile){
string s;
while(getline(infile,s))
ret++;
}
return ret;
}
void bianlifile(stack<string> &st,ostream &out=cout)
{
string top=st.top();
string temp=top;
st.pop(); //退栈
const char *currentpath=temp.c_str();//string ->const char *
temp+=xiegang;
temp+=filegeshi2;
const char *tempath=temp.c_str();
struct _finddata_t temfile;//文件(夹)结构
long handle= _findfirst(tempath,&temfile);//第一个 kendingshi .
if(handle!=-1)
{
_findnext(handle,&temfile);//第二个肯定是 ..
}//if(handle!=-1)
while(!_findnext(handle,&temfile))
{
if(temfile.attrib==_A_SUBDIR)
{
string pushname;//加入堆栈的名字
pushname+=currentpath;
pushname+=xiegang;
pushname+=temfile.name;
st.push(pushname);
// cout<<"foder:"<<pushname<<endl;
}//如果是文件夹,则加入堆栈
else//否则,判断是不是要找的文件格式,并统计行数
{
string tems=temfile.name;
unsigned pos=tems.find(filetype);
if(pos!=-1)
if(pos+filetype.size()==tems.size())
{//find filetype
string temname;
temname+=currentpath;
temname+=xiegang;
temname+=temfile.name;
int temh=countsofhangshu(temname);
out<<temname<<":"<<temh<<endl;
hangshu+=countsofhangshu(temname);//统计行数
}
}
}//while next
}
int main(int argc, char *argv[])
{
stack<string> s1;
s1.push(panfu);
int max1=0;//进栈最大值
cout<<"如果盘符下放置比如e:放置文件则不能检测到"<<endl;
ofstream outfile("out.txt");
while(s1.empty()==0){
if(max1<s1.size())
max1=s1.size();
bianlifile(s1,outfile);//遍历整个盘符
}
cout<<"max:size"<<max1;
cout<<"Total:"<<hangshu;
system("PAUSE");
return EXIT_SUCCESS;
}