-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinecount.c
More file actions
60 lines (46 loc) · 1.25 KB
/
Copy pathlinecount.c
File metadata and controls
60 lines (46 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
static long count_lines_in_file(const char *path) {
FILE *f = fopen(path, "r");
if (!f) return 0;
long lines = 0;
int c;
while ((c = fgetc(f)) != EOF) {
if (c == '\n') lines++;
}
fclose(f);
return lines;
}
static long count_lines_recursive(const char *dir_path) {
DIR *dir = opendir(dir_path);
if (!dir) return 0;
struct dirent *entry;
struct stat st;
char path[1024];
long total = 0;
while ((entry = readdir(dir)) != NULL) {
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
continue;
snprintf(path, sizeof(path), "%s/%s", dir_path, entry->d_name);
if (stat(path, &st) == 0) {
if (S_ISDIR(st.st_mode)) {
total += count_lines_recursive(path);
} else if (S_ISREG(st.st_mode)) {
total += count_lines_in_file(path);
}
}
}
closedir(dir);
return total;
}
int main(int argc, char **argv) {
if (argc < 2) {
printf("usage: %s <dir>\n", argv[0]);
return 1;
}
long total = count_lines_recursive(argv[1]);
printf("total lines: %ld\n", total);
return 0;
}