#include "stdafx.h" #include <stdio.h> #include <windows.h> #include <fstream> #include <iostream> #include <string> using namespace std; int g_nFileNum =0 ; BOOL IsRoot(LPCTSTR lpszPath) { TCHAR szRoot[4]; wsprintf(szRoot, "%c://", lpszPath[0]); return (lstrcmp(szRoot, lpszPath) == 0); } int CalcCodeLine(LPCTSTR lpszPath) { char szFileExt[MAX_PATH]={'/0'}; _splitpath( lpszPath, NULL, NULL, NULL, szFileExt ); if( strcmp(szFileExt , ".h") ==0 || strcmp(szFileExt , ".H") ==0 || strcmp(szFileExt , ".c") ==0 || strcmp(szFileExt , ".C") ==0 || strcmp(szFileExt , ".cpp") ==0 || strcmp(szFileExt , ".CPP") ==0 ) { long lCount=0; string str; ifstream file(lpszPath); while (!file.fail()) { getline(file, str); if( str !="" ) { lCount++; } } return lCount; } return -1; } void FindInAll(::LPCTSTR lpszPath) { TCHAR szFind[MAX_PATH]; lstrcpy(szFind, lpszPath); if (!IsRoot(szFind)) lstrcat(szFind, "//"); lstrcat(szFind, "*.*"); // 找所有文件 WIN32_FIND_DATA wfd; HANDLE hFind = FindFirstFile(szFind, &wfd); if (hFind == INVALID_HANDLE_VALUE) // 如果没有找到或查找失败 return; do { if (wfd.cFileName[0] == '.') continue; // 过滤这两个目录 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { TCHAR szFile[MAX_PATH]; if (IsRoot(lpszPath)) { wsprintf(szFile, "%s%s", lpszPath, wfd.cFileName); } else { wsprintf(szFile, "%s//%s", lpszPath, wfd.cFileName); } FindInAll(szFile); // 如果找到的是目录,则进入此目录进行递归 } else { TCHAR szFile[MAX_PATH]; if (IsRoot(lpszPath)) { wsprintf(szFile, "%s%s", lpszPath, wfd.cFileName); } else { wsprintf(szFile, "%s//%s", lpszPath, wfd.cFileName); } int n = CalcCodeLine(szFile) ;// 对文件进行操作 if( n !=-1 ) { printf("%s,%d/r/n",szFile,n); g_nFileNum+=n; } } } while (FindNextFile(hFind, &wfd)); FindClose(hFind); // 关闭查找句柄 } int main(int argc, char* argv[]) { if( argc !=2 || argv[1]=="" ) { return -1; } FindInAll( argv[1] ); printf("total lines=%d/r/n",g_nFileNum); system("pause"); return 0; }