#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#define PATHMAX 255
void getdir(char *path);
void searchdir(char *path);
void statlines(char *filepath);
int total = 0;
int main(void)
{
char dirpath[PATHMAX];
getdir(dirpath);
searchdir(dirpath);
printf("Total lines = %d\n", total);
return 0;
}
void getdir(char *path)
{
int i = 0, ch;
printf("Please input the full path of the catalog:");
while (i < PATHMAX && (ch = getchar()) != '\n')
path[i++] = ch;
path[i] = '\0';
}
void searchdir(char *path)
{
DIR *dp;
struct dirent *dmsg;
char addpath[PATHMAX] = {'\0'}, *tmpstr;
if ((dp = opendir(path)) == NULL)
{
perror("opendir");
exit(-1);
}
while ((dmsg = readdir(dp)) != NULL)
{
if (!strcmp(dmsg->d_name, ".") || !strcmp(dmsg->d_name, ".."))
continue;
strcpy(addpath, path);
strcat(addpath, "/");
strcat(addpath, dmsg->d_name);
if (dmsg->d_type == 4)
searchdir(addpath);
else if (dmsg->d_type == 8)
{
if ((tmpstr = strrchr(dmsg->d_name, '.')) == NULL)
continue;
if (!strcmp(tmpstr, ".c") || !strcmp(tmpstr, ".h"))
statlines(addpath);
}
}
closedir(dp);
}
void statlines(char *filepath)
{
int cout_lines = 0;
char ch;
FILE *fc;
if ((fc = fopen(filepath, "r")) == NULL)
{
perror("fopen");
exit(-1);
}
while ((ch = getc(fc)) != EOF)
if (ch == '\n')
cout_lines++;
printf("%s Lines = %d\n", filepath, cout_lines);
total += cout_lines;
if (fclose(fc) != 0)
perror("fclose");
}