|
发表于 2024-2-13 16:30:12
|
显示全部楼层
我只能显示计算中,所以我自己学着写了新的#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#define MAX_FILE_SIZE 10000
int count_lines(char *filename) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("无法打开文件 %s\n", filename);
return 0;
}
int count = 0;
char line[MAX_FILE_SIZE];
while (fgets(line, sizeof(line), file) != NULL) {
count++;
}
fclose(file);
return count;
}
int count_lines_recursive(char *dir_path) {
DIR *dir = opendir(dir_path);
if (dir == NULL) {
printf("无法打开目录 %s\n", dir_path);
return 0;
}
int total_lines = 0;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
char entry_path[MAX_FILE_SIZE];
sprintf(entry_path, "%s/%s", dir_path, entry->d_name);
struct stat entry_info;
if (stat(entry_path, &entry_info) == -1) {
printf("无法获取文件信息:%s\n", entry_path);
continue;
}
if (S_ISDIR(entry_info.st_mode)) {
// 忽略 "." 和 ".." 目录
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 递归处理子目录并累加代码行数
total_lines += count_lines_recursive(entry_path);
} else if (S_ISREG(entry_info.st_mode) && strstr(entry->d_name, ".exe") == NULL) {
// 处理普通文件,排除 .exe 文件
int lines = count_lines(entry_path);
printf("%s: %d 行\n", entry_path, lines);
total_lines += lines;
}
}
closedir(dir);
return total_lines;
}
int main() {
char current_dir[MAX_FILE_SIZE];
if (getcwd(current_dir, sizeof(current_dir)) == NULL) {
printf("无法获取当前目录\n");
return 1;
}
printf("当前目录:%s\n", current_dir);
printf("开始统计代码行数...\n");
int total_lines = count_lines_recursive(current_dir);
printf("所有目录中代码行数的总和为:%d\n", total_lines);
printf("统计完成!\n");
return 0;
}
|
|