有时我们需要统计一下代码的行数,作为一个工作量的考评项。所以就写了这段小程序。
/** 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;}