利用windows提供的目录操作库和文件操作库,统计指定目录及其子目录中所有.cpp、.c、.h文件的代码量,用来检测自己的编程工作量()。
1 #include <stdio.h> 2 #include <string.h> 3 #include <direct.h> 4 #include <malloc.h> 5 #include <io.h> 6 7 long nLen = 0; 8 int GetFileLength(char *pszPath) 9 { 10 FILE *pRead = fopen(pszPath, "r"); 11 if (NULL == pRead) 12 { 13 return -1; 14 } 15 char szBuf[1024]; 16 while (!feof(pRead)) 17 { 18 fgets(szBuf, sizeof(szBuf), pRead); 19 nLen++; 20 } 21 22 fclose(pRead); 23 24 } 25 int SearchPath(char *pszPath) 26 { 27 int rv = 0; 28 rv = chdir(pszPath); 29 if (0 != rv) 30 { 31 printf("func chdir() error\n"); 32 rv = -1; 33 return rv; 34 } 35 36 struct _finddata_t data; 37 long handle; 38 if (-1L == (handle = _findfirst("*.*", &data))) //成功返回唯一的搜索句柄, 出错返回-1 39 { 40 return rv; 41 } 42 do 43 { 44 if (data.attrib == _A_SUBDIR ) 45 {//目录类型 46 char szBuf[1024] = {0}; 47 if (strcmp(data.name, ".") != 0 && strcmp(data.name, "..") != 0) 48 { 49 sprintf(szBuf, "%s\\%s", pszPath, data.name); 50 SearchPath(szBuf); 51 } 52 } 53 else 54 {//单个文件 55 int nLen = strlen(data.name); 56 if (data.name[nLen - 1] == ‘p‘ && data.name[nLen - 2] == ‘p‘ && 57 data.name[nLen - 3] == ‘c‘ &&data.name[nLen - 4] == ‘.‘ ) 58 {//过滤出所有cpp的文件 59 printf(" [%s]\n", data.name ); 60 char szBuf[1024] = {0}; 61 sprintf(szBuf, "%s\\%s", pszPath, data.name); 62 GetFileLength(szBuf); 63 } 64 } 65 } while(_findnext( handle, &data ) == 0); //成功返回0 , 出错返回-1 66 67 _findclose( handle ); // 关闭当前句柄 68 69 return rv; 70 } 71 72 int main() 73 { 74 char *pszPath = "L:\\谷歌大赛"; 75 SearchPath(pszPath); 76 printf("总代码量为:%ld\n", nLen); 77 return 0; 78 }