|
发表于 2023-9-10 15:30:46
|
显示全部楼层
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#define MAX_PATH 256
int countLines(const char *filename);
void findAllCodes(const char *path);
void findAllFiles(const char *path);
int countLines(const char *filename)
{
FILE *fp;
int count = 0;
int temp;
if ((fp = fopen(filename, "r")) == NULL)
{
fprintf(stderr, "无法打开文件:%s\n", filename);
return 0;
}
while ((temp = fgetc(fp)) != EOF)
{
if (temp == '\n')
{
count++;
}
}
fclose(fp);
return count;
}
void findAllCodes(const char *path)
{
DIR *dir;
struct dirent *entry;
char targetPath[MAX_PATH], filePath[MAX_PATH];
if ((dir = opendir(path)) == NULL)
{
fprintf(stderr, "无法打开路径:%s\n", path);
return;
}
while ((entry = readdir(dir)) != NULL)
{
sprintf(filePath, "%s/%s", path, entry->d_name);
if (entry->d_type == DT_REG && strstr(entry->d_name, ".c") != NULL)
{
int fileCount = countLines(filePath);
printf("文件:%s,行数:%d\n", filePath, fileCount);
}
else if (entry->d_type == DT_DIR && strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0)
{
sprintf(targetPath, "%s/%s", path, entry->d_name);
findAllCodes(targetPath);
}
}
closedir(dir);
}
void findAllFiles(const char *path)
{
DIR *dir;
struct dirent *entry;
char targetPath[MAX_PATH];
if ((dir = opendir(path)) == NULL)
{
fprintf(stderr, "无法打开路径:%s\n", path);
return;
}
while ((entry = readdir(dir)) != NULL)
{
sprintf(targetPath, "%s/%s", path, entry->d_name);
if (entry->d_type == DT_DIR && strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0)
{
findAllCodes(targetPath);
findAllFiles(targetPath);
}
}
closedir(dir);
}
int main()
{
char path[MAX_PATH] = ".";
printf("计算中...\n");
findAllCodes(path);
findAllFiles(path);
return 0;
}
|
|