Created
September 23, 2014 12:26
-
-
Save JesseEisen/2f7079781674818a104a to your computer and use it in GitHub Desktop.
Countline program, written by C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <errno.h> | |
#include <dirent.h> /*some functions option on dir*/ | |
#include <sys/stat.h> | |
#define MAXLINE 200 | |
int linecount=0; /*for save the countline*/ | |
int getLine(char *fname) | |
{ | |
FILE *fp; | |
char line[MAXLINE]; | |
int total = 0; | |
fp = fopen(fname,"r"); | |
while(fgets(line,200,fp) != NULL) | |
total++; | |
return total; | |
} | |
/*Recurse a the target dirent*/ | |
void Recur_dir(const char *dir, int depth) | |
{ | |
DIR *dp; /*dir pointer*/ | |
struct dirent *entry; /*structure to save dir info*/ | |
struct stat statbuf; /*use to charge which is dir and which is file*/ | |
/*get the decriptor*/ | |
if((dp = opendir(dir)) == NULL) | |
{ | |
printf("cannot open directory:%s\n",dir); | |
fprintf(stderr,"opendir error:%s\n",strerror(errno)); | |
exit(1); | |
} | |
chdir(dir); /*enter into target dir*/ | |
while((entry = readdir(dp)) != NULL) | |
{ | |
lstat(entry->d_name,&statbuf);/*get the entry status*/ | |
if(S_ISDIR(statbuf.st_mode)) | |
{ | |
/*is a dirctory and ignore the .. and .*/ | |
if(strcmp(".",entry->d_name)== 0 || strcmp("..",entry->d_name) == 0) | |
continue; | |
//printf("%*s%s\n",depth,"",entry->d_name); | |
Recur_dir(entry->d_name,depth+4); /*continue to open */ | |
} | |
else /*if not a dirctroy and we count the line*/ | |
{ | |
linecount += getLine(entry->d_name); /*count everyfile line*/ | |
} | |
} | |
chdir(".."); | |
closedir(dp); | |
} | |
int main(int argc, const char *argv[]) | |
{ | |
if(argc != 2) | |
{ | |
printf("Usage:%s dir\n",argv[0]); | |
exit(1); | |
} | |
Recur_dir(argv[1],0); | |
printf("Total:%d\n",linecount); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment