600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 统计代码行数的小工具

统计代码行数的小工具

时间:2022-11-27 02:57:56

相关推荐

统计代码行数的小工具

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

/** Name: zfcntl.c* Author:zhoufanking* Date: 6/28/** 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 <stdio.h>#include <sys/types.h>#include <dirent.h>#include <malloc.h>#include <assert.h>#include <sys/stat.h>#include <stdlib.h>#include <string.h>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;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。