统计代码行数的小工具

有时我们需要统计一下代码的行数,作为一个工作量的考评项。所以就写了这段小程序。

/** Name:        zfcntl.c* Author:      zhoufanking* Date:        6/28/2008** Purpose:*      Get a file or dir name form command line,count how many lines*      in the file or files under the dir.*      This is useful when you count the number of lines in your code.* Usage:*      1.      gcc -o zfcntl zfcntl.c*      2.      ./zfcntl  file_name/dir_name*/#include #include #include #include #include #include #include #include static int totallines = 0;void  dopath(const char *pathname);void usage(void)__attribute__((__noreturn__));int  countf(const char *fname);int main(int argc, char **argv){if(argc != 2)usage();char *fpath = argv[1];struct stat stinfo;if ( lstat(fpath,&stinfo) < 0)perror("lstat error!/n");if(S_ISDIR(stinfo.st_mode) != 0)dopath(fpath);elseif(S_ISREG(stinfo.st_mode) != 0)totallines =  countf(fpath);printf("%s contains %d lines./n",fpath,totallines);return 0;}void dopath(const char *pathname){DIR *dr;struct dirent *dp; struct stat *statinfo;statinfo = (struct stat*) malloc(sizeof(struct stat));assert(statinfo);char *fullpath;fullpath = (char *) malloc( 1024*sizeof(char));assert(fullpath);memset(fullpath,0,sizeof(fullpath));strcat(fullpath,pathname);dr = opendir(fullpath);if(!dr){perror("open dir failed!/n");free (fullpath);free (statinfo);fullpath = NULL;statinfo = NULL;exit (-1);}while( (dp = readdir(dr) ) != NULL){   if(dp->d_name[0] =='.')continue;strcat(fullpath,dp->d_name);if (lstat(fullpath,statinfo)<0)perror("dopath():lstat error/n");if( S_ISDIR(statinfo->st_mode)!=0){strcat(fullpath,"/");dopath(fullpath);}else    // encounter a regular file, count the lines number{totallines += countf(fullpath);}memset(fullpath,0,sizeof(fullpath));strcat(fullpath,pathname);}closedir(dr);free (fullpath);free (statinfo);fullpath = NULL;statinfo = NULL;}void usage(){printf("Usage:cntl filename/directotyname/n");exit(-1);}int countf(const char *fname){FILE *fp;int  cur;int linescnt = 0;if( fp = fopen(fname,"r"),fp==NULL ){printf("count():cannot open file %s/n",fname);return -1;}fseek(fp,0,SEEK_SET);      while(cur = fgetc(fp),cur != EOF){if(cur == '/n')linescnt++;elsecontinue;}fclose(fp);return linescnt;}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部