glxhyt

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  15 随笔 :: 0 文章 :: 4 评论 :: 0 Trackbacks

 

 

                       
  
   

结果:
     

 1/*****************************************************************
 2 * 鏂囦欢鍚?    锛? Head.h
 3 * 鍒涘缓鏃堕棿     锛?2010锛?锛?9
 4 * 浣滆€?        锛?閮緳
 5 * 浣滅敤        锛?鍏敤鐨勫ご鏂囦欢
 6 ******************************************************************/

 7
 8#ifndef HEADFILE_H_
 9#define HEADFILE_H_
10
11#include <iostream>
12#include <string>
13#include <sstream>
14#include <cstdlib>
15#include "logging.h"
16#include "Error.h"
17using namespace Error;
18
19using namespace std;
20
21enum enType{File = 0, Dir = 1};
22///////////////////////////////////////////////////////////////
23// 瀛樺偍鍙傛暟鐨勭粨鏋勪綋
24struct tagParameterInfo_t
25{
26  string strInputPath;
27  string strOutPutPath;
28  string strFileType;
29  string  bSubDir;
30  string  nOutPutView;
31  string strHelp;
32  enType Type;
33  tagParameterInfo_t():strInputPath(""), strOutPutPath(""),
34                       strFileType("c:cpp:h"),bSubDir("true"),
35                       nOutPutView("3"),strHelp(""), Type(Dir)
36  {
37
38  }

39}
;
40
41#endif
42


 

 1/*****************************************************************
 2 * 鏂囦欢鍚?    锛?DirLineInfo.h
 3 * 鍒涘缓鏃堕棿     锛?2010锛?锛?9
 4 * 浣滆€?        锛?閮緳
 5 * 浣滅敤        锛?鐩綍绫荤殑鏋勫缓CDirLineInfo鐨勬瀯閫狅紝缁熻鐩綍鐨勮淇℃伅
 6 *           锛?鏋勫缓鏂囦欢瀛愮洰褰曞拰瀛愭枃浠剁殑閾捐〃
 7 ******************************************************************/

 8#ifndef DIRLINEINFO_H_
 9#define DIRLINEINFO_H_
10
11#include "LineInfo.h"
12#include "FileLineInfo.h"
13#include <sys/types.h>
14#include <dirent.h>
15#include <unistd.h>
16#include <pcre++.h>
17#include <pcrecpp.h>
18
19class CFileLineInfo;
20
21class CDirLineInfo: public CLineInfo
22{
23friend ostream& operator<<(ostream&out, CDirLineInfo& Dir);
24public:
25    CDirLineInfo();
26    CDirLineInfo(char *pDirPath);
27    virtual ~CDirLineInfo();
28
29public:
30    CDirLineInfo& operator+ (  const CDirLineInfo& DirLineInfo);
31    CDirLineInfo& operator+ (  const CFileLineInfo& FileLineInfo);
32
33    string GetWriteXmlInfo();
34
35public:
36
37    CFileLineInfo *m_pSubFileListHead;
38    CDirLineInfo  *m_pSubDirListHead;
39
40    CDirLineInfo  *m_pNext;
41public:
42    string m_strDirName;
43    int    m_nFileCount;
44}
;
45
46#endif /* DIRLINEINFO_H_ */
47
48
49
50
51
52
53

 

  1/*****************************************************************
  2 * 文件名     : DirLineInfo.cpp
  3 * 创建时间     : 2010-9-19
  4 * 作者         : 郭龙
  5 * 作用        :    目录类的构建CDirLineInfo的构造,统计目录的行信息
  6 *           : 构建文件子目录和子文件的链表
  7 ******************************************************************/

  8
  9#include "DirLineInfo.h"
 10
 11extern tagParameterInfo_t ParameterInfo;
 12
 13CDirLineInfo::CDirLineInfo():m_pSubFileListHead(NULL), m_pSubDirListHead(NULL), m_pNext(NULL),m_nFileCount(0),m_strDirName("")
 14{
 15    // TODO Auto-generated constructor stub
 16
 17}

 18///////////////////////////////////////////////////////////////
 19// 目录类的构建CDirLineInfo的构造,统计目录的行信息
 20// 构建文件子目录和子文件的链表
 21CDirLineInfo::CDirLineInfo(char* strDirPath):m_pSubFileListHead(NULL), m_pSubDirListHead(NULL), m_pNext(NULL), m_nFileCount(0)
 22//CDirLineInfo::CDirLineInfo(char* strDirPath): m_pNext(NULL), m_nFileCount(0)
 23{
 24     m_strDirName = strDirPath;
 25
 26     /* o. right
 27      *
 28      *  CFileLineInfo* pFileTemp = new CFileLineInfo;
 29      *  CDirLineInfo*  pDirTemp =  new CDirLineInfo;
 30      *  m_pSubFileListHead = pFileTemp;
 31      *  m_pSubDirListHead  =  pDirTemp;
 32      *
 33      *
 34      */

 35
 36     /* o. wrong
 37      *
 38      *     CFileLineInfo  FileLineHead;
 39      *     CDirLineInfo   DirLineHead;
 40      *     m_pSubFileListHead = &FileLineHead;
 41      *     m_pSubDirListHead =  &DirLineHead;
 42      *
 43      *       stack or heap
 44     */

 45
 46     /*2  */
 47      m_pSubFileListHead = new CFileLineInfo;
 48      m_pSubDirListHead =  new CDirLineInfo;
 49      CFileLineInfo *pFileTemp = m_pSubFileListHead;
 50      CDirLineInfo  *pDirTemp  = m_pSubDirListHead;
 51
 52
 53     struct dirent *ptr;
 54     DIR *pDir = opendir(strDirPath);
 55     while( NULL != (ptr = readdir(pDir)))
 56     {
 57         string strd_name(ptr->d_name);
 58         if((strd_name == string(".")) || (strd_name == string("..")))
 59                       continue;
 60
 61         string strPathName(strDirPath);
 62         string strDirName(ptr->d_name);
 63         strPathName = strPathName + "/" + strDirName;
 64
 65         if((NULL != (opendir(strPathName.c_str()))) && ("true" == ParameterInfo.bSubDir))
 66         {
 67             pDirTemp->m_pNext = new CDirLineInfo((char*)strPathName.c_str());
 68
 69             if(pDirTemp->m_pNext->m_Total != pDirTemp->m_pNext->m_NULL)
 70             {
 71                 pDirTemp = pDirTemp->m_pNext;
 72                (*this= (*this+  *(pDirTemp);
 73             }

 74             else
 75             {
 76                 delete pDirTemp->m_pNext;
 77                 pDirTemp->m_pNext = NULL;
 78             }

 79         }

 80         else
 81         {
 82               Pcre regc(".*\\.c$",PCRE_CASELESS);
 83               Pcre regh(".*\\.h$",PCRE_CASELESS);
 84               Pcre regcpp(".*\\.cpp$",PCRE_CASELESS);
 85
 86               Pcre regctype("c",PCRE_CASELESS);
 87               Pcre reghtype("h",PCRE_CASELESS);
 88               Pcre regcpptype("cpp",PCRE_CASELESS);
 89               string strFileType = ParameterInfo.strFileType;
 90               string strFileTypeC = ParameterInfo.strFileType;
 91               if(strFileType.find("cpp"!= string::npos)
 92               {
 93                   strFileTypeC.erase(strFileTypeC.find("cpp"), 3);
 94               }

 95               if( (true == regc.search(strd_name) && true == regctype.search(strFileTypeC))
 96                   || (true == regh.search(strd_name) && true == reghtype.search(strFileType))
 97                   || (true == regcpp.search(strd_name) && true == regcpptype.search(strFileType)))
 98                  {
 99                      pFileTemp->m_pNext =  new CFileLineInfo((char*)strPathName.c_str());
100                      if(pFileTemp->m_pNext->m_Total != pFileTemp->m_pNext->m_NULL)
101                      {
102                         ++ m_nFileCount;
103                         pFileTemp = pFileTemp->m_pNext;
104                         (*this= (*this+ *(pFileTemp);
105                      }

106                      else
107                      {
108                          delete pFileTemp->m_pNext;
109                          pFileTemp->m_pNext = NULL;
110                      }

111                    //  cout<<*(pFileTemp)<<endl;
112                  }

113
114         }

115
116     }

117   //  cout<<(*this)<<endl;
118}

119///////////////////////////////////////////////////////////////
120// 目录类行信息 = 目录类行信息 + 子文件类行信息
121CDirLineInfo& CDirLineInfo::operator+ (  const CDirLineInfo& DirLineInfo)
122{
123
124    this->m_code += DirLineInfo.m_code;
125    this->m_Total += DirLineInfo.m_Total;
126    this->m_comment += DirLineInfo.m_comment;
127    this->m_NULL +=  DirLineInfo.m_NULL;
128    this->m_nFileCount += DirLineInfo.m_nFileCount;
129
130    return (*this);
131
132}

133///////////////////////////////////////////////////////////////
134// 目录类行信息 = 目录类行信息 + 子目录类行信息
135CDirLineInfo& CDirLineInfo::operator+ (  const CFileLineInfo& FileLineInfo)
136{
137    this->m_code += FileLineInfo.m_code;
138    this->m_Total += FileLineInfo.m_Total;
139    this->m_comment += FileLineInfo.m_comment;
140    this->m_NULL +=  FileLineInfo.m_NULL;
141
142    return (*this);
143}

144///////////////////////////////////////////////////////////////
145// 输出操作符的重载 方便调试用的
146ostream& operator<<(ostream&out, CDirLineInfo& Dir)
147{
148    out<<"Dir : "<< Dir.m_strDirName<<endl;
149    out<<"m_code: "<<Dir.m_code<<endl;
150    out<<"m_comment: "<<Dir.m_comment<<endl;
151    out<<"m_NULL: "<<Dir.m_NULL<<endl;
152    out<<"m_Total: "<<Dir.m_Total<<endl;
153    out<<"m_nFileCount: "<<Dir.m_nFileCount<<endl;
154    return out;
155}

156///////////////////////////////////////////////////////////////
157// 把行信息转换到string类型
158string CDirLineInfo::GetWriteXmlInfo()
159{
160    stringstream stream;
161
162    string strCount = "";
163    stream<<m_nFileCount;
164    stream>>strCount;
165    stream.clear();
166
167    string strCode = "";
168    stream<<m_code;
169    stream>>strCode;
170    stream.clear();
171
172    string strTotal = "";
173    stream<<m_Total<<endl;
174    stream>>strTotal;
175    stream.clear();
176
177    string strComment = "";
178    stream<<m_comment;
179    stream>>strComment;
180    stream.clear();
181
182    string strNULL = "";
183    stream<<m_NULL;
184    stream>>strNULL;
185    stream.clear();
186
187    string strTemp = m_strDirName;
188    strTemp = "path=\"" + strTemp + "\"" +
189            " Count=\""   + strCount +"\"" +
190            " Code=\"" + strCode + "\"" +
191            " Tatol=\"" + strTotal + "\"" +
192            " Comment=\""+ strComment + "\"" +
193            " NULL=\""+  strNULL + "\"";
194
195    return strTemp;
196}

197///////////////////////////////////////////////////////////////
198// 析构函数:释放子目录和自文件的头指针
199CDirLineInfo::~CDirLineInfo()
200{
201    // TODO Auto-generated destructor stub
202    delete m_pSubFileListHead;
203    delete m_pSubDirListHead;
204}

205
206
207

 

 

/*****************************************************************
 * 文件名     : Error.h
 * 创建时间     : 2010-9-19
 * 作者         : 郭龙
 * 作用        :    用于抛出异常
 *****************************************************************
*/

#ifndef ERROR_H_
#define ERROR_H_
namespace Error {

    
struct Syntax_error {
        
const char* p;
        Syntax_error(
const char* q) { p = q; }
    }
;
}


#endif /* ERROR_H_ */





 

 1/*****************************************************************
 2 * 文件名     : FileLineInfo.h
 3 * 创建时间     : 2010-9-19
 4 * 作者         : 郭龙
 5 * 作用        : 文件类的构造,统计文件的行信息
 6 ******************************************************************/

 7
 8#ifndef FILELINEINFO_H_
 9#define FILELINEINFO_H_
10
11#include "LineInfo.h"
12#include "HeadFile.h"
13#include <pcre++.h>
14#include <pcrecpp.h>
15#include <fstream>
16using namespace pcrepp;
17
18class CFileLineInfo: public CLineInfo
19{
20
21    friend ostream& operator<<(ostream& out, CFileLineInfo& FileLine);
22public:
23    CFileLineInfo();
24    CFileLineInfo(char* pFilePath);
25    virtual ~CFileLineInfo();
26    string GetWriteXmlInfo();
27
28private:
29    void ReaseString(string& str, bool &bFlag);
30    void Reasestring2(string &str, bool &bFlag);
31    void DeleteString(string &strTemp, bool &bFlag);
32public:
33    CFileLineInfo *m_pNext;
34public:
35    string m_strFileName;
36}
;
37
38#endif /* FILELINEINFO_H_ */
39

 

  1/*****************************************************************
  2 * 文件名     : FileLineInfo.cpp
  3 * 创建时间     : 2010-9-19
  4 * 作者         : 郭龙
  5 * 作用        : 文件类的构造,统计文件的行信息
  6 ******************************************************************/

  7
  8#include "FileLineInfo.h"
  9
 10CFileLineInfo::CFileLineInfo():m_pNext(NULL), m_strFileName("")
 11{
 12    // TODO Auto-generated constructor stub
 13
 14}

 15
 16CFileLineInfo::~CFileLineInfo()
 17{
 18    // TODO Auto-generated destructor stub
 19}

 20///////////////////////////////////////////////////////////////
 21//  统计行信息:
 22CFileLineInfo::CFileLineInfo(char* pFilePath):m_pNext(NULL)
 23{
 24       ifstream fin(pFilePath);
 25       int whiteLine = 0;
 26       int commentLine = 0;
 27       bool comment = false;
 28       int  normalLine = 0;
 29       char tmp[256= {0};
 30       int nTemp1 = 0;
 31       bool bflag = false;
 32       bool cflag = false;
 33       bool dflag = false;
 34       string strTemp1 = "";
 35       while(fin.getline(tmp, 256))
 36       {
 37           string strTemp = string(tmp);
 38           Pcre reg1("^[\\s]*$", PCRE_DOTALL);                   //   /     空白行
 39           Pcre reg2("^[\\s]*//.*", PCRE_DOTALL);                //   /     空白// 行
 40           Pcre reg3("/\\*.*", PCRE_DOTALL);                     //   /     /* =   空白/*  + 代码/*
 41           Pcre reg4("^[\\s]*/\\*.*", PCRE_DOTALL);              //   /       空白/*
 42           Pcre reg5("(.*)\\*/", PCRE_DOTALL);                   //   /      */ = 代码 */ +  */代码 \* + */代码 /*  */  /*
 43           Pcre reg6("\\*/(.*)/\\*", PCRE_DOTALL);               //          */  /*= */ 代码 /* + */ /*
 44           Pcre reg7("/\\*.*\\*/", PCRE_DOTALL);                 //           /*    */
 45           Pcre reg8("\\*/[\\s]*$", PCRE_DOTALL);                //   /        */ 空白
 46           Pcre reg9("\\*/.*/\\*.*", PCRE_DOTALL);               //          */  /*= */ 代码 /* + */ /*
 47           Pcre reg10("\".*[/\\*\\*///]+.*\"", PCRE_DOTALL);     //         "  后面有反斜杠
 48           Pcre reg11("//.*[/\\*\\*/]+.*", PCRE_DOTALL);         //        //  /*  */ = // /* */ +  代码// /* */
 49
 50           Pcre reg16(".*(\"|//){1}.*\\\\[\\s]*$", PCRE_DOTALL);  //  /    " // 后面有反斜杠
 51           Pcre reg17(".*\".*\\\\[\\s]*$", PCRE_DOTALL);          //      " // 后面有反斜杠
 52           Pcre reg18(".*\\\\[\\s]*$", PCRE_DOTALL);              //  /       后面有反斜杠
 53
 54           //  处理 /*  */ +  /*  */int a = 0; /*  */  + /*  */ /* */
 55           if ((true == reg4.search(strTemp)) && (true == reg8.search(strTemp)))
 56            {
 57                  ReaseString(strTemp, bflag);  //   删除 /*  */
 58                  if(true == reg1.search(strTemp))
 59                  {
 60                    commentLine ++;
 61                  }

 62                  else
 63                  {
 64                      normalLine ++;
 65                  }

 66                  continue;
 67            }

 68
 69            DeleteString(strTemp, bflag);        //   删除 /*  */ 和 " /* "
 70           // 处理  " // 后面有反斜杠
 71           if(true == reg16.search(strTemp))
 72           {
 73               nTemp1 ++;
 74               strTemp.erase(strTemp.rfind("\\"),1); //  删除  反斜杠
 75               strTemp1 += strTemp;
 76               dflag = true;
 77               cflag = true;
 78               continue;
 79           }

 80           //   处理  " // 后面有反斜杠 多行情况
 81           if(cflag == true)
 82           {
 83               if(true == reg18.search(strTemp))
 84               {
 85                  strTemp1 += strTemp;
 86                  nTemp1 ++;
 87                  continue;
 88               }

 89               else
 90               {
 91                   strTemp1 += strTemp;
 92                   cflag = false;
 93               }

 94           }

 95          //  处理  " // 后面有反斜杠 多行情况 合并的字符串:
 96          if(true == dflag)
 97           {
 98            unsigned int npos1 = ((strTemp1.find(("\""),0 )!= string::npos)? strTemp1.find("\""):225);
 99            unsigned int npos2 = ((strTemp1.find(("//"), 0!= string::npos)? strTemp1.find("//"):225);
100              if(npos1 > npos2)                           //  //   后面有反斜杠
101              {
102                  commentLine += nTemp1;
103                  if(false == reg2.search(strTemp1))
104                  {
105                     normalLine ++;
106                     commentLine--;                      //增加的是 /前面的那个
107                  }

108                  DeleteString(strTemp1, bflag);         //   删除 /*  */ 和 " /* "
109              }

110              else                                      //  代码行:“ 后面有反斜杠  //不会出现npos1 == npos2
111              {
112                  normalLine += nTemp1;
113                  DeleteString(strTemp1, bflag);        //   删除 /*  */ 和 " /* "
114              }

115              nTemp1 = 0;
116          }

117         //处理  " // 后面有反斜杠 多行情况 设置控制变量
118         if(true == dflag)
119         {
120             strTemp = strTemp1;
121             strTemp1 = "";
122             dflag = false;
123         }

124        // 统计  空白//
125        if (true == reg2.search(strTemp))
126        {
127              commentLine ++;
128        }

129        //  /* =   空白/*  + 代码/*
130        else if (true == reg3.search(strTemp) && (false == reg5.search(strTemp)) )
131        {
132             if(true == reg4.search(strTemp))
133             {
134              commentLine ++;
135             }

136            else
137              {
138                normalLine ++;
139              }

140             comment = true;
141       }

142       // 处理 */ = 代码 */ +  */代码 \* + */代码 /*  */  /*
143       else if (comment)
144       {
145              commentLine ++;
146              if(true == reg5.search(strTemp))
147              {
148                  if(true == reg8.search(strTemp))
149                  {
150                      comment = false;
151                  }

152                  else
153                  {
154                      normalLine ++;
155                      commentLine --;
156                      comment = false;
157                  }

158                  if(bflag == true)            // bfalg 是为了标记 /*   */   /*这种情况:
159                  {
160                      comment = true;
161                      bflag   = false;
162                  }

163              }

164        }

165       // 统计 空白行
166       else  if(true == reg1.search(strTemp))
167           {
168                  whiteLine ++;
169           }

170       // 统计 代码行
171       else
172       {
173             normalLine ++;
174       }

175
176   }

177
178       m_code = normalLine;
179       m_comment = commentLine;
180       m_NULL = whiteLine;
181       m_Total = normalLine + commentLine + whiteLine;
182       m_strFileName = pFilePath;
183
184       fin.close();
185}

186///////////////////////////////////////////////////////////////
187// 删除   /*    */  和 “  /*  */ "
188void CFileLineInfo::DeleteString(string &strTemp, bool &bFlag)
189{
190    Pcre reg7("/\\*.*\\*/", PCRE_DOTALL);                 //           /*    */
191    Pcre reg8("\\*/[\\s]*$", PCRE_DOTALL);                //   /        */ 空白
192    Pcre reg9("\\*/.*/\\*.*", PCRE_DOTALL);               //          */  /*= */ 代码 /* + */ /*
193    Pcre reg10("\".*[/\\*\\*///]+.*\"", PCRE_DOTALL);     //         "  后面有反斜杠
194    Pcre reg11("//.*[/\\*\\*/]+.*", PCRE_DOTALL);         //        //  /*  */ = // /* */ +  代码// /* */
195
196   if(true == reg11.search(strTemp) && (false == bFlag) )
197   {
198       unsigned int nTempPos = strTemp.find("//"0);
199       if((nTempPos !=  string::npos) && ( (nTempPos+ 2 ) < strTemp.size()))
200       {
201          strTemp.erase((strTemp.find("//"0+ 2));
202       }

203   }

204    if(true == reg7.search(strTemp) && true == reg10.search(strTemp))
205    {
206          unsigned int nBegPos = strTemp.find("/*"0);
207          unsigned int nEndPos = strTemp.find("\"", 0);
208          if(nBegPos > nEndPos)
209          {
210              Reasestring2( strTemp, bFlag);
211          }

212          else
213          {
214              ReaseString(strTemp, bFlag);
215          }

216    }

217    if(true == reg7.search(strTemp))
218    {
219        ReaseString(strTemp, bFlag);
220    }

221   if(true == reg10.search(strTemp))
222   {
223       Reasestring2( strTemp, bFlag);
224   }

225
226}

227///////////////////////////////////////////////////////////////
228// 删除   /*    */
229void CFileLineInfo::ReaseString(string& str, bool &bFlag)
230{
231    Pcre reg14("\".*[/\\*\\*///]+.*\"", PCRE_DOTALL);
232    unsigned int nBegPos = str.find("/*"0);
233    unsigned int nEndPos = str.find("*/"0);
234    if(nBegPos > nEndPos)
235    {
236       nEndPos = str.find("*/", nEndPos+2);
237    }

238    while((nBegPos != string::npos) && (nEndPos != string::npos))
239    {
240         str.erase(nBegPos, nEndPos - nBegPos + 2);
241
242            if(true == reg14.search(str))
243            {
244               Reasestring2( str, bFlag);
245            }

246         nBegPos = str.find("/*");
247         nEndPos  = str.find("*/", nEndPos+2);
248    }

249    nEndPos = str.find("/*"0);
250    nBegPos = str.find("*/"0);
251    if((nEndPos != string::npos ) && (nBegPos != string::npos))
252    {
253        str.erase(nEndPos, str.size() - nEndPos);
254        bFlag = true;
255    }

256}

257///////////////////////////////////////////////////////////////
258// 删除   " /*  "
259void CFileLineInfo::Reasestring2(string &str, bool &bFlag)
260{
261    Pcre reg15("/\\*.*\\*/", PCRE_DOTALL);   //   if /*  abc+ */           else    not daima
262    unsigned int nBegPos = str.find("\"", 0);
263    unsigned int nTempPos = str.find("\\\"",nBegPos +1);
264    while(nTempPos != string::npos)
265    {
266        str.erase(nTempPos, 2);
267        nTempPos = str.find("\\\"", nTempPos + 2);
268    }

269    unsigned int nEndPos = str.find("\"", nBegPos+ 1);
270    while((nBegPos != string::npos) && (nEndPos != string::npos) && (nBegPos < (nEndPos - 1)))
271    {
272         str.erase(nBegPos+1, nEndPos - nBegPos - 1 );
273            if(true == reg15.search(str))
274            {
275                ReaseString(str, bFlag);
276            }

277
278        nBegPos = str.find("\"",0);
279        nEndPos = str.find("\"", nBegPos + 1);
280     }

281}

282///////////////////////////////////////////////////////////////
283// 把行信息转换成string类型:
284string CFileLineInfo::GetWriteXmlInfo()
285{
286    stringstream stream;
287
288    string strCode = "";
289    stream<<m_code;
290    stream>>strCode;
291    stream.clear();
292
293    string strTotal = "";
294    stream<<m_Total<<endl;
295    stream>>strTotal;
296    stream.clear();
297
298    string strComment = "";
299    stream<<m_comment;
300    stream>>strComment;
301    stream.clear();
302
303    string strNULL = "";
304    stream<<m_NULL;
305    stream>>strNULL;
306    stream.clear();
307
308    string strTemp = m_strFileName;
309    strTemp = "path=\"" + strTemp + "\"" +
310            " Code=\"" + strCode + "\"" +
311            " Tatol=\"" + strTotal + "\"" +
312            " Comment=\""+ strComment + "\"" +
313            " NULL=\""+  strNULL + "\"";
314
315//    return strTemp;
316    RETURN(strTemp);
317}

318///////////////////////////////////////////////////////////////
319// 操作符重载 方便调试:
320ostream& operator<<(ostream& out, CFileLineInfo& FileLine)
321{
322    out<<"File: "<<FileLine.m_strFileName<<endl;
323    out<<"m_code: "<<FileLine.m_code<<endl;
324    out<<"m_comment: "<<FileLine.m_comment<<endl;
325    out<<"m_NULL: "<<FileLine.m_NULL<<endl;
326    out<<"m_Total: "<<FileLine.m_Total<<endl;
327
328    return out;
329}

330
331
332
333

 

 1/*****************************************************************
 2 * 文件名     : DirLineInfo.cpp
 3 * 创建时间     : 2010-9-19
 4 * 作者         : 郭龙
 5 * 作用        : Line Class
 6 ******************************************************************/

 7
 8#ifndef LINEINFO_H_
 9#define LINEINFO_H_
10
11class CLineInfo
12{
13public:
14    int m_code;
15    int m_Total;
16    int m_comment;
17    int m_NULL;
18
19public:
20    CLineInfo();
21    virtual ~CLineInfo();
22}
;
23
24#endif /* LINEINFO_H_ */
25

 

 1/*****************************************************************
 2 * 文件名     : LineInfo.cpp
 3 * 创建时间     : 2010-9-19
 4 * 作者         : 郭龙
 5 * 作用        : LineInfo Class
 6 ******************************************************************/

 7
 8#include "LineInfo.h"
 9#include  "HeadFile.h"
10CLineInfo::CLineInfo():m_code(0), m_Total(0), m_comment(0), m_NULL(0)
11{
12    // TODO Auto-generated constructor stub
13}

14
15CLineInfo::~CLineInfo()
16{
17    // TODO Auto-generated destructor stub
18}

19

 

 1/*****************************************************************
 2 * 文件名     : DirLineInfo.cpp
 3 * 创建时间     : 2010-9-19
 4 * 作者         : 郭龙
 5 * 作用        : Read ParameterInfo And Write XML File
 6 ******************************************************************/

 7#ifndef OPERATOR_H_
 8#define OPERATOR_H_
 9#include "HeadFile.h"
10#include "FileLineInfo.h"
11#include "DirLineInfo.h"
12#include<libxml/parser.h>
13#include<libxml/tree.h>
14#include <time.h>
15#include <sys/time.h>
16#include <ctype.h>
17#define  INTTOCHAR(i)         (streamInToCharp<<i,\
18                              streamInToCharp>>StrInToCharp,\
19                              streamInToCharp.clear(),\
20                              (char*)(StrInToCharp.c_str()) )\
21
22class CDirLineInfo;
23class CFileLineInfo;
24
25extern tagParameterInfo_t ParameterInfo;
26
27class COperator
28{
29
30public:
31    static void ReadOutPutParameterInfo(int &argv , char **argc);
32    static void OpenMainDir();
33    static void WriteDirFileXmlHead();
34    static void WriteDirXml(CDirLineInfo *DirLineInfo, xmlNodePtr pXmlNode);
35    static void WriteFileXml(xmlNodePtr pXmlNode);
36    static void WriteFile(CDirLineInfo *DirLineInfo);
37    static void PrintEndl(int i);
38    static void PrintHelpInfo();
39    static void IsFileTypeParameter(string strFileType);
40    static string GetDateAndTimeString();
41
42public:
43     static CFileLineInfo m_FileLineInfoRoot;
44     static CDirLineInfo m_DirLineInfoRoot;
45     static string StrInToCharp;
46     static stringstream streamInToCharp;
47     static ofstream out;
48
49}
;
50
51#endif /* OPERATOR_H_ */
52

  

  1/*****************************************************************
  2 * 文件名     : DirLineInfo.cpp
  3 * 创建时间     : 2010-9-19
  4 * 作者         : 郭龙
  5 * 作用        : Read ParameterInfo And Write XML File
  6 ******************************************************************/

  7
  8#include "Operator.h"
  9
 10string COperator::StrInToCharp = "";
 11stringstream COperator::streamInToCharp;
 12CDirLineInfo COperator::m_DirLineInfoRoot;
 13CFileLineInfo COperator::m_FileLineInfoRoot;
 14
 15ofstream COperator::out;
 16//////////////////////////////////////////////////
 17//读取参数:并进行判断
 18void COperator::ReadOutPutParameterInfo(int &argv , char **argc)
 19{
 20       string strUser = getenv("HOME");
 21
 22       if( argv > 1)
 23       {
 24         if(0 == strcmp(argc[1], "--h"))
 25         {
 26           COperator::PrintHelpInfo();
 27           exit(1);
 28         }

 29       }

 30
 31      if(argv < 5)
 32      {
 33          throw Error::Syntax_error("Parameter is short ,please input again: ");
 34      }

 35
 36       if(0 == strcmp(argc[1], "--h"))
 37       {
 38          COperator::PrintHelpInfo();
 39           exit(1);
 40       }

 41      if(0 != strcmp(argc[1], "-pin"))
 42      {
 43          throw Error::Syntax_error("-pin parameter is wrong, please input path again: ");
 44      }

 45      else
 46      {
 47          ParameterInfo.strInputPath = argc[2];
 48          if(ParameterInfo.strInputPath.substr(02== "..")
 49          {
 50              ParameterInfo.strInputPath.erase(0,2);
 51              ParameterInfo.strInputPath = strUser + ParameterInfo.strInputPath ;
 52          }

 53      }

 54      if(0 != strcmp(argc[3], "-pout"))
 55      {
 56          throw Error::Syntax_error("-pout parameter is wrong, please Output path again: ");
 57      }

 58      else
 59      {
 60          ParameterInfo.strOutPutPath = argc[4];
 61          if(ParameterInfo.strOutPutPath.substr(02== "..")
 62          {
 63              ParameterInfo.strOutPutPath.erase(02);
 64              ParameterInfo.strOutPutPath = strUser + ParameterInfo.strOutPutPath;
 65          }

 66          ofstream fout(ParameterInfo.strOutPutPath.c_str());
 67          if(NULL == fout)
 68          {
 69              throw Error::Syntax_error("OutPutxml is wrong, please Output path again: ");
 70          }

 71          fout.close();
 72      }

 73      if(argv > 5)
 74      {
 75          int nTemp = 5;
 76          int nCurrentArgc = -1;
 77          while(nTemp < argv)
 78          {
 79
 80              static int nCountArgc = 0;
 81              if(nCountArgc <= nCurrentArgc)
 82              {
 83                  cout<<"please input right Parameter"<<endl;
 84                  COperator::PrintHelpInfo();
 85                  exit(1);
 86              }

 87              nCurrentArgc = nCountArgc;
 88              if(0 == strcmp(argc[nTemp], "-suffix"&& argc[nTemp+1!= NULL)
 89              {
 90                   Pcre reg12("^[\\s]*([ch]:|\\bcpp\\b:){1,2}([ch]|\\bcpp\\b){1}[\\s]*$", PCRE_CASELESS);
 91                   Pcre reg13("^[\\s]*([ch]|\\bcpp\\b){1}[\\s]*$", PCRE_CASELESS);
 92
 93                   string strTemp(argc[nTemp+1] );
 94                   if(true == reg12.search(strTemp) || true == reg13.search(strTemp))
 95                   {
 96                       char *pTemp = argc[nTemp+1];
 97                       for(unsigned int i=0; i < strlen(pTemp); ++i)
 98                       {
 99                           pTemp[i] = tolower(pTemp[i]);
100                       }

101                       strTemp = pTemp;
102                      //判断c:cpp:C 这种类型:
103                      COperator::IsFileTypeParameter(strTemp);
104
105                      ParameterInfo.strFileType = argc[nTemp+1];
106                      nTemp = nTemp +2;
107                      ++ nCountArgc;
108                  }

109                  else
110                  {
111                      throw Error::Syntax_error("-suffix parameter is wrong ,please input: ");
112                  }

113              }

114              else  if(0 == strcmp(argc[nTemp], "-r"&& argc[nTemp+1!= NULL)
115              {
116                  if(( 0 == strcmp(argc[nTemp+1], "true"))
117                    || (0 == strcmp(argc[nTemp+1], "false")))
118                  {
119                      ParameterInfo.bSubDir = argc[nTemp+1];
120                      nTemp = nTemp + 2;
121                      ++ nCountArgc;
122                  }

123                  else
124                  {
125                      throw Error::Syntax_error("-r parameter is wrong ,please input: ");
126                  }

127              }

128              else if(0 == strcmp(argc[nTemp], "-view"&& argc[nTemp+1!= NULL)
129              {
130                  if(( 0 == strcmp(argc[nTemp+1], "1"))
131                    || (0 == strcmp(argc[nTemp+1], "2"))
132                    || (0 == strcmp(argc[nTemp+1], "3")))
133                  {
134                      ParameterInfo.nOutPutView = argc[nTemp+1];
135                      nTemp = nTemp + 2;
136                      ++ nCountArgc;
137                  }

138                  else
139                  {
140                      throw Error::Syntax_error("-view parameter is wrong ,please input: ");
141                  }

142              }

143              else if0 == strcmp(argc[nTemp], "--h"))
144              {
145                  COperator::PrintHelpInfo();
146                  exit(1);
147              }

148              else
149              {
150              }

151          }

152      }

153
154}

155//////////////////////////////////////////////////
156//打开输入的路径,判断是目录还是文件
157void COperator::OpenMainDir()
158{
159
160     struct dirent *ptr = NULL;
161     DIR *pDir = opendir(ParameterInfo.strInputPath.c_str());
162     Pcre regc(".*\\.c$",PCRE_CASELESS);
163     Pcre regh(".*\\.h$",PCRE_CASELESS);
164     Pcre regcpp(".*\\.cpp$",PCRE_CASELESS);
165     if(pDir != 0)
166     {
167         (COperator::m_DirLineInfoRoot).m_pNext = new CDirLineInfo::CDirLineInfo((char*)ParameterInfo.strInputPath.c_str());
168     }

169     else if(   true == regc.search(ParameterInfo.strInputPath)
170             ||    true == regh.search(ParameterInfo.strInputPath)
171             || true == regcpp.search(ParameterInfo.strInputPath) )
172     {
173              ParameterInfo.Type = File;
174              (COperator::m_FileLineInfoRoot).m_pNext = new CFileLineInfo::CFileLineInfo((char*)ParameterInfo.strInputPath.c_str());
175     }

176     else
177     {
178         throw Error::Syntax_error("InPut path is Error ,please input new path: ");
179     }

180
181}

182//////////////////////////////////////////////////
183//写入目录或者文件xml 结构的Head 信息
184void COperator::WriteDirFileXmlHead()
185{
186
187      xmlDocPtr doc = xmlNewDoc(BAD_CAST"1.0");
188      xmlNodePtr  root_node = xmlNewNode(NULL, BAD_CAST"LineCounter");
189      xmlDocSetRootElement(doc, root_node);
190      if(ParameterInfo.Type == Dir)
191      {
192         xmlNewProp(root_node,BAD_CAST"Input",BAD_CAST ((COperator::m_DirLineInfoRoot).m_pNext)->m_strDirName.c_str());
193      }

194      else if(ParameterInfo.Type == File)
195      {
196          xmlNewProp(root_node,BAD_CAST"Input",BAD_CAST ((COperator::m_FileLineInfoRoot).m_pNext)->m_strFileName.c_str());
197      }

198      else
199      {
200
201      }

202      xmlNewProp(root_node,BAD_CAST"Time",BAD_CAST GetDateAndTimeString().c_str());
203      xmlNewProp(root_node,BAD_CAST"suffix",BAD_CAST ParameterInfo.strFileType.c_str() );
204      xmlNewProp(root_node,BAD_CAST"Recursive",BAD_CAST ParameterInfo.bSubDir.c_str());
205      xmlNewProp(root_node,BAD_CAST"View",BAD_CAST ParameterInfo.nOutPutView.c_str());
206
207       //创建一个节点,设置其内容和属性,然后加入根结点
208      xmlNodePtr node = xmlNewNode(NULL, BAD_CAST"Result");
209      xmlAddChild(root_node,node);
210
211        if(ParameterInfo.Type == Dir)
212        {
213              out.open("LineCounter.txt");
214              cout<<".txt Write To LineCounter.txt "<<endl;
215              WriteFile((COperator::m_DirLineInfoRoot).m_pNext);
216              out.close();
217              xmlNewProp(node,BAD_CAST"Count",BAD_CAST INTTOCHAR((COperator::m_DirLineInfoRoot).m_pNext->m_nFileCount));
218              xmlNewProp(node,BAD_CAST"Code",BAD_CAST INTTOCHAR((COperator::m_DirLineInfoRoot).m_pNext->m_code));
219              xmlNewProp(node,BAD_CAST"Tatol",BAD_CAST INTTOCHAR((COperator::m_DirLineInfoRoot).m_pNext->m_Total));
220              xmlNewProp(node,BAD_CAST"Comment",BAD_CAST INTTOCHAR((COperator::m_DirLineInfoRoot).m_pNext->m_comment));
221              xmlNewProp(node,BAD_CAST"Null",BAD_CAST INTTOCHAR((COperator::m_DirLineInfoRoot).m_pNext->m_NULL));
222              COperator::WriteDirXml(((COperator::m_DirLineInfoRoot).m_pNext),  root_node);
223        }

224        else if(ParameterInfo.Type == File)
225        {
226              xmlNewProp(node,BAD_CAST"Code",BAD_CAST  INTTOCHAR((COperator::m_FileLineInfoRoot).m_pNext->m_code));
227              xmlNewProp(node,BAD_CAST"Tatol",BAD_CAST INTTOCHAR((COperator::m_FileLineInfoRoot).m_pNext->m_Total));
228              xmlNewProp(node,BAD_CAST"Comment",BAD_CAST INTTOCHAR((COperator::m_FileLineInfoRoot).m_pNext->m_comment));
229              xmlNewProp(node,BAD_CAST"Null",BAD_CAST INTTOCHAR((COperator::m_FileLineInfoRoot).m_pNext->m_NULL));
230
231              WriteFileXml(root_node);
232        }

233        else
234        {
235
236        }

237
238        int nRel = xmlSaveFile(ParameterInfo.strOutPutPath.c_str(), doc);
239        if(nRel != -1)
240        {
241            cout<<" xml write Path: "<<ParameterInfo.strOutPutPath <<endl;
242        }

243        else
244        {
245            throw Error::Syntax_error("xml Path is Wrong, please");
246        }

247
248        xmlFreeDoc(doc);
249
250}

251//////////////////////////////////////////////////
252//把输入路径是目录的信息。写入xml文件中
253void COperator::WriteDirXml(CDirLineInfo *DirLineInfo, xmlNodePtr pXmlNode)
254{
255
256  if(NULL !=  DirLineInfo)
257     {
258
259        CDirLineInfo *pDirLineTemp = NULL;
260        CFileLineInfo *pFileLineTemp = NULL;
261        pDirLineTemp = DirLineInfo->m_pSubDirListHead->m_pNext;
262        pFileLineTemp = DirLineInfo->m_pSubFileListHead->m_pNext;
263
264        while(NULL != pFileLineTemp)
265        {
266            if(ParameterInfo.nOutPutView != string("1"))
267            {
268               xmlNodePtr  FileSon = xmlNewNode(NULL, BAD_CAST"File");
269               xmlAddChild(pXmlNode, FileSon);
270
271               xmlNewProp(FileSon,BAD_CAST"Path",BAD_CAST pFileLineTemp->m_strFileName.c_str());
272               xmlNewProp(FileSon,BAD_CAST"Code",BAD_CAST INTTOCHAR(pFileLineTemp->m_code));
273               xmlNewProp(FileSon,BAD_CAST"Tatol",BAD_CAST INTTOCHAR(pFileLineTemp->m_Total));
274               xmlNewProp(FileSon,BAD_CAST"Comment",BAD_CAST INTTOCHAR(pFileLineTemp->m_comment));
275               xmlNewProp(FileSon,BAD_CAST"Null",BAD_CAST INTTOCHAR(pFileLineTemp->m_NULL));
276            }

277            pFileLineTemp = pFileLineTemp->m_pNext;
278        }

279        while((NULL != pDirLineTemp) )
280        {
281                if(ParameterInfo.nOutPutView == string("2"))
282                {
283                    WriteDirXml(pDirLineTemp, pXmlNode);
284                }

285                else
286                {
287                      xmlNodePtr  DirSon = xmlNewNode(NULL, BAD_CAST"Dir");
288                      xmlAddChild(pXmlNode, DirSon);
289
290                   xmlNewProp(DirSon,BAD_CAST"Path",BAD_CAST pDirLineTemp->m_strDirName.c_str());
291                   xmlNewProp(DirSon,BAD_CAST"Count",BAD_CAST INTTOCHAR(pDirLineTemp->m_nFileCount));
292                   xmlNewProp(DirSon,BAD_CAST"Code",BAD_CAST INTTOCHAR(pDirLineTemp->m_code));
293                   xmlNewProp(DirSon,BAD_CAST"Tatol",BAD_CAST INTTOCHAR(pDirLineTemp->m_Total));
294                   xmlNewProp(DirSon,BAD_CAST"Comment",BAD_CAST INTTOCHAR(pDirLineTemp->m_comment));
295                   xmlNewProp(DirSon,BAD_CAST"Null",BAD_CAST INTTOCHAR(pDirLineTemp->m_NULL));
296                   WriteDirXml(pDirLineTemp, DirSon);
297                }

298
299            pDirLineTemp = pDirLineTemp->m_pNext;
300        }

301
302
303     }

304}

305//////////////////////////////////////////////////
306//把输入路径是文件的信息。写入xml文件中
307void COperator::WriteFileXml(xmlNodePtr pXmlNode)
308{
309       xmlNodePtr  FileSon = xmlNewNode(NULL, BAD_CAST"File");
310       xmlAddChild(pXmlNode, FileSon);
311       CFileLineInfo *pFileLineTemp  = (COperator::m_FileLineInfoRoot).m_pNext;
312
313       xmlNewProp(FileSon,BAD_CAST"Path",BAD_CAST pFileLineTemp->m_strFileName.c_str());
314       xmlNewProp(FileSon,BAD_CAST"Code",BAD_CAST INTTOCHAR(pFileLineTemp->m_code));
315       xmlNewProp(FileSon,BAD_CAST"Tatol",BAD_CAST INTTOCHAR(pFileLineTemp->m_Total));
316       xmlNewProp(FileSon,BAD_CAST"Comment",BAD_CAST INTTOCHAR(pFileLineTemp->m_comment));
317       xmlNewProp(FileSon,BAD_CAST"Null",BAD_CAST INTTOCHAR(pFileLineTemp->m_NULL));
318}

319//////////////////////////////////////////////////
320//  帮助信息
321void COperator::PrintHelpInfo()
322{
323    cout<<"--h: help  "<<endl;
324    cout<<"The useage of linecounter pragram as follow:"<<endl;
325    cout<<"-pin: input arg, input a path of directory of file: "<<endl;
326    cout<<"-pout: output arg, output a result of the count info: "<<endl;
327    cout<<"-suffix: h:c:cpp, file type:"<<endl;
328    cout<<"-r:  ture/false count subDir or not:  "<<endl;
329    cout<<"-view : 1.only Dir Write Xml, 2. only File Write xml. 3. Dir and File Write xml"<<endl;
330    cout<<"Example: -pin /home/guolong -pout line.xml -r true"<<endl;
331}

332//////////////////////////////////////////////////
333//  获取当前时间的函数
334string COperator::GetDateAndTimeString()
335 {
336
337      struct timeval t2;
338      stringstream stream;
339      gettimeofday(&t2, NULL);
340      struct tm *ptm = localtime(&t2.tv_sec);
341      string strYear = "";
342      stream<<ptm->tm_year + 1900;
343      stream>>strYear;
344      stream.clear();
345      string strMon = "";
346      stream<<ptm->tm_mon + 1;
347      stream>>strMon;
348      stream.clear();
349      string strDay = "";
350      stream<<ptm->tm_mday;
351      stream>>strDay;
352      stream.clear();
353      string strHour = "";
354      stream<<ptm->tm_hour;
355      stream>>strHour;
356      stream.clear();
357      string strMin = "";
358      stream<<ptm->tm_min;
359      stream>>strMin;
360      stream.clear();
361      string strSec = "";
362      stream<<ptm->tm_sec;
363      stream>>strSec;
364      stream.clear();
365      string strUsec = "";
366      stream<<t2.tv_usec;
367      stream>>strUsec;
368
369      string strDateTime = strYear + "-" + strMon + "-" + strDay + " " +
370                           strHour + ":" + strMin + ":" + strSec + "." + strUsec;
371      RETURN(strDateTime);
372
373 }

374//////////////////////////////////////////////////
375//  写入文件中xml格式的函数
376void COperator::WriteFile(CDirLineInfo *DirLineInfo)
377{
378        static int nCountBlack = 0;
379        int nCurrentBlack = nCountBlack;
380        if(nCurrentBlack == 0)
381        {
382            out<<"<?xml version=\"1.0\"?>"<<endl;
383            out<<"<LineCounter "
384                <<"Input=\""<<DirLineInfo->m_strDirName<<"\" Time =\""
385                <<COperator::GetDateAndTimeString()<<"\" suffix=\""
386                <<ParameterInfo.strFileType<<"\" Recursive=\""
387                <<ParameterInfo.bSubDir<<"\" View=\""
388                <<ParameterInfo.nOutPutView<<"\">"<<endl;
389        }

390        else
391        {
392            PrintEndl(nCurrentBlack);
393            out<<"<Dir ";
394            out<<(*DirLineInfo).GetWriteXmlInfo();
395            out<<endl;
396        }

397        CDirLineInfo *pDirLineTemp;
398        CFileLineInfo *pFileLineTemp;
399        pDirLineTemp = DirLineInfo->m_pSubDirListHead->m_pNext;
400        pFileLineTemp = DirLineInfo->m_pSubFileListHead->m_pNext;
401        while(NULL != pFileLineTemp)
402        {
403            //ReadFile(pFileLineTemp);
404            PrintEndl(nCurrentBlack + 1);
405            out<<"<File ";
406            out<<(*pFileLineTemp).GetWriteXmlInfo();
407            pFileLineTemp = pFileLineTemp->m_pNext;
408            out<<"/>"<<endl;
409        }

410        while(NULL != pDirLineTemp)
411        {
412            ++ nCountBlack;
413            WriteFile(pDirLineTemp);
414
415            nCountBlack = nCurrentBlack;
416            pDirLineTemp = pDirLineTemp->m_pNext;
417        }

418
419        if(nCurrentBlack != 0)
420        {
421            PrintEndl(nCurrentBlack);
422            out<<"</Dir>"<<endl;
423        }

424        else
425        {
426            out<<"</LineCounter>"<<endl;
427        }

428}

429
430void COperator::PrintEndl(int i)
431{
432    for(int j = 0; j < i; j++)
433        out<<" ";
434}

435//////////////////////////////////////////////////
436//   判断c:cpp:C 这种类型:
437void COperator::IsFileTypeParameter(string strFileType)
438{
439
440       string strTemp = strFileType;
441       unsigned int nSubPosBeg = 0;
442       unsigned int nSubposEnd = 0;
443       int nCountc = 0;
444       int nCounth = 0;
445       int nCountcpp = 0;
446       nSubposEnd = strTemp.find(":");
447       while(nSubposEnd != string::npos)
448       {
449         if(strTemp.substr(nSubPosBeg,  nSubposEnd - nSubPosBeg) == "cpp")
450         {
451             ++ nCountcpp;
452         }

453         else if(strTemp.substr(nSubPosBeg, nSubposEnd - nSubPosBeg) == "h")
454         {
455             ++ nCounth;
456         }

457         else
458         {
459             ++ nCountc;
460         }

461
462        nSubPosBeg = nSubposEnd+1;
463        nSubposEnd = strTemp.find(":", nSubposEnd + 2); /// 曾在这里错了,注意 + 2
464
465       }

466
467       if(strTemp.substr(nSubPosBeg, strTemp.size() - nSubPosBeg) == "cpp")
468       {
469            ++ nCountcpp;
470       }

471       else if(strTemp.substr(nSubPosBeg, strTemp.size() - nSubPosBeg) == "h")
472       {
473            ++ nCounth;
474       }

475       else
476       {
477           ++ nCountc;
478       }

479
480      if((nCountc > 1|| (nCounth > 1|| (nCountcpp > 1))
481      {
482          throw Error::Syntax_error("-suffix parameter is wrong ,please input: ");
483      }

484}

485
486
487
488
489
490
491

 

 1/*****************************************************************
 2 * 文件名     : LineCounter.cpp
 3 * 创建时间     : 2010-9-19
 4 * 作者         : 郭龙
 5 * 作用        :    主函数main()文件
 6 ******************************************************************/

 7
 8#include <iostream>
 9#include "Operator.h"
10#include "HeadFile.h"
11#include  "DirLineInfo.h"
12#include  "FileLineInfo.h"
13#include<stdio.h>
14#include<libxml/parser.h>
15#include<libxml/tree.h>
16using namespace std;
17
18tagParameterInfo_t ParameterInfo;
19
20int main(int argv ,char ** argc)
21{
22    LogInit();
23    try
24    {
25        COperator::ReadOutPutParameterInfo(argv, argc);
26        COperator::OpenMainDir();
27        COperator::WriteDirFileXmlHead();
28    }

29    catch(Error::Syntax_error e)
30    {
31        cerr << "syntax error:" << e.p << "\n";
32    }

33    RETURN(0);
34}

35
36
37
38
39
40
41
42
43


LineCounter心得

一.LineCounter简介:    
     实现一个有配置的代码行统计工具,需要使用我们之前实现的liblogging.so库,尽可能提高性能。详细见:LineCounter 需求分析:

二.LineCounter功能:

        用户可以通过输入的参数来输出所需的信息:

     -pin:必选参数;输入文件或者目录路径,支持相对路径

     -pout:必选参数;输出文件路径(包含文件名)。

       -suffix: 可选参数; 支持文件的类型。默认值c:h:cpp

     -r:可选参数;是否统计子目录。默认值:true/false

     -view: 可选参数;显示目录,文件还是都显示1.目录 2.文件3.目录和文件

     --h : 帮助信息

     举例说明:

./linecounter  -pin /home/guolong –pout linecounter.xml –r true

 三.学习心得:

这个程序做了两个星期,学习到许多知识,主要有以下几点:

  1. 树形结构。
  2. 正则表达式
  3. libxml2库
  4. log库

四. 具体描述:

1. 树形结构

因为目录结构是一个树形结构,因此在刚开始的时候我考虑了左孩子右兄弟结构来实现总体结构。但是这种结构有几次遍历树才能统计到用户所需要的行信息。最后经过老师的指点。构造了主目录类且在里面聚合一个子目录指针和子文件指针(也即是现在的结构)

 

 

1.1开始的时候写了一个递归遍历目录和文件名的函数:

2.正则表达式

 

 1int ReadDir(const char *pName,)
 2
 3{
 4
 5 DIR *pDir = opendir(pName);
 6
 7 struct dirent *ptr;
 8
 9 if(0 == pDir)
10
11   {
12
13    // .c .h .cpp
14
15     cout<<"File pName: "<<pName<<endl;
16
17     closedir(pDir);
18
19     return 0;
20
21   }
22
23   else
24
25   {
26
27     cout<<"Dir PName: "<<pName<<endl;
28
29   }
30
31   while( NULL != (ptr = readdir(pDir)))
32
33 {
34
35         if((string(ptr->d_name) == string(".")) || ((string(ptr->d_name) == string(".."))))
36
37                 continue;
38
39         string strPathName(pName);
40
41         string strDirName(ptr->d_name);
42
43         strPathName = strPathName + "/" + strDirName;
44
45         ReadDir(strPathName.c_str() );
46
47     }
48
49     closedir(pDir);
50
51 return 0;
52
53}
54
55

 

2.1查询资料学习了正则表达式及库的连接:

《正则表达式30十分钟入门教程》名字有点俗,但是短短十一页,基本语法都包含了,我看很受益。

2.2查询这则表达式的库。

好几个库,但是最后选了个既好安装,又好用的pcre库

安装:

         下面安装pcrecpp

sudo apt-get install libpcre++-dev

            sudo apt-get install libpcre++0

            连接库

            在Eclipse设置里面库里面包换pcre++

            头文件:

#include <pcre++.h>

#include <pcrecpp.h>

using namespace pcrepp;

2.3 几个正则表达式

                Pcre reg1("^[\\s]*$", PCRE_DOTALL); //whiteLine

                Pcre reg2("^[\\s]*//.*", PCRE_DOTALL);    //        whilteLile//

                Pcre reg3("/\\*.*", PCRE_DOTALL);       //   love/* or whilteLile/*

                Pcre reg4("^[\\s]*/\\*.*", PCRE_DOTALL); //       whilteLile/*       

                Pcre reg5("(.*)\\*/", PCRE_DOTALL);                 //   */ = abc */ + abc */(abc )\* + */

                Pcre reg6("\\*/(.*)/\\*", PCRE_DOTALL);       // abc */ abc or white /*

                Pcre reg7("\\*/[^\\s]+/\\*", PCRE_DOTALL);   //   if */ abc+ /*           

                Pcre reg8("\\*/[\\s]*$", PCRE_DOTALL);    // */whiteLine____            

                Pcre reg9("\\*/.*/\\*.*", PCRE_DOTALL);

 

 

 

简单说一下:

 

. 匹配除换行符以外的任何字符

\w 匹配字母或者数字或下划线或汉字

\s 匹配任意的空白符

\d 匹配数字

\b 匹配单词的开始或结束

^   匹配字符串的开始

$   匹配字符串的结束

 

之所以用 \\s 是用于转移字符。

 

2.4  一个正则表达式的测试例子

       3. libxml2库

   3.1查询资料学习了libxml2及库的连接

     C++的XML编程经验――LIBXML2库使用指南

http://www.blogjava.net/wxb_nudt/archive/2007/11/ 18/161340.html

这个作者把libxml2写的很好,我感觉比教材都好,看了他的这个文章我掌握了libxml2简单实用。下面是一个部分的截图:详情查询上面网站:

 

库的连接:

   在头文件包含 /usr/include/libxml2

   在库文件里面 xml2

 

 

4.log库

4.1 预处理

#if

 #else

 #endif

 一种是为了注释,一种是为了便与错误时,重复调用函数:

 

  #if FATAL    

      #define FATAL(info) fatal(info);

   #else   

      #define FATAL(info) NULL; 

#endif

 

4.2注意不要把ifstream fout; getline(fout , str, '\n');

    写成ofstream

 

4.3可以把ofstream fout,定义类的成私有的,在初始化的时候

    使用 fout.open("/home/ganhm/.loging/loging.conf");

         if(NULL == fout)

        cout<<"da kai shi bai"<<endl;

4.4.以后程序尽量不要赋值粘贴,尽量自己写:

  

   c 语言可以传FILE流 而 c++ 不可以传:

 

4.5 区分:/home/ganhm/

    和\home\ganhm\

      \\

      \[

4.6.注意三文件格式:

 

4.7使用函数指针,

 

4.8注意static的参数,和函数的使用,如:Factory工厂。

 

在定义时候注意static一定要初始化。

 

 如:

 class A

 {

   private:

 static int m_inum;

   public:

 static int Fun();

 };

 int A::m_inum = 0; //注意不能在构造函数里面初始化,不能

                     //在前面加上static

 int A::Fun();

 

4.9 一个关于流转化:

    #include<fstream>

    ofstream fout(1.txt);

    streambuf *x = cout.rduf(fout.rduf());

    cout.rdbuf(x);

例子:

    void WriteLog(struct timeval t2, string file2,

                   unsigned int id2, string function2,

                   int line2, char *info2 ,int type2)

{

        streambuf *x = NULL;

        if(type2 == 1)

        {

               x = cout.rdbuf(fout.rdbuf());

        }

       ptm = localtime(&t2.tv_sec);

       cout<<ptm->tm_year+1900<<"-"<<ptm->tm_mon+1<<"-"<<ptm->tm_mda;

       cout<<"-"<<ptm->tm_hour<<":"<<ptm->tm_min<<":"<<ptm->tm_sec<<".";

       cout<<t2.tv_usec;

       file2 = FileMainPath::GetFileMainPaht() + file2.substr( file2.find('/') );

       cout<<" "<<id2;

       cout<<" "<<function2;

       cout<<" "<<file2;

       cout<<":"<<line2;

       cout<<" "<<"Info"<<info2;

 

        if(type2 == 1)

           cout.rdbuf(x);

 

}

 

4.10.一个关与流转化

 #include<sstream>

 stringstream stream;

 int num;

 stream<<str;

 stream>>num;

 //注意还有一个函数是stream.clear();

 

4.11一个关于变量参数:#include <cstdarg>

 

              va_list argptr;

              va_start(argptr, info);

              char buffer[256];

              vsprintf( buffer,info,argptr);

              va_end(argptr);

4.12关于一个时间的:#include <time.h>

                 #include <sys/time.h>

                 struct timeval t_time;

                 gettimeofday(&t_time, NULL);

                 ptm = localtime(&t1.tv_sec);

                 out<<ptm->tm_year+1900<<"-"<<ptm->tm_mon+1<<"-"<<ptm->tm_mday;                out<<"-"<<ptm->tm_hour<<":"<<ptm->tm_min<<":"<<ptm->tm_sec<<"."; out<<t1.tv_usec;

4.13几个常用的宏

 __TIME__

 __FUNCTION__

 __LINE__

 syscall(224)

 __DATE__

 

4.14  stringstream stream 补充:

    在到底是文件操作,还是控制台,还是XML

    可以先把所有数据写到一个 stream流里面:

   然后:在cout>>str;

            fout>>str;

            xout>>str;

附录1:

    构造链表时遇到的一个问题:空指针,关于堆栈

/* o. right

          *

      * CFileLineInfo* pFileTemp = new CFileLineInfo;

      * CDirLineInfo* pDirTemp = new CDirLineInfo;

          * m_pSubFileListHead = pFileTemp;

          * m_pSubDirListHead = pDirTemp;

          *

          *

          */

 

          /* o. wrong

          *

          *     CFileLineInfo FileLineHead;

          *     CDirLineInfo   DirLineHead;

      *     m_pSubFileListHead = &FileLineHead;

      *     m_pSubDirListHead = &DirLineHead;

          *

          *       stack or heap

     */

 

          /*2 */

      m_pSubFileListHead = new CFileLineInfo;

      m_pSubDirListHead = new CDirLineInfo;

     CFileLineInfo *pFileTemp = m_pSubFileListHead;

          CDirLineInfo *pDirTemp = m_pSubDirListHead;

 

     

 

posted on 2010-09-26 21:11 郭龙 阅读(1509) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理