查看自己已写的代码行数的程序

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>

#define MAX 256

long total;

int countLines(const char *filename);
int isCode(const char *filename);
void findAllDirs(const char *path);

int countLines(const char *filename)
{
        FILE *fp;
        int count = 0;
        int temp;

        if ((fp = fopen(filename, "r")) == NULL)
        {
                fprintf(stderr, "Can not open the file: %s\n", filename);
                return 0;
        }

        while ((temp = fgetc(fp)) != EOF)
        {
                if (temp == '\n')
                {
                        count++;
                }
        }

        fclose(fp);

        return count;
}

int isCode(const char *filename)
{
        int length;

        length = strlen(filename);
        
        if (!strcmp(filename + (length - 2), ".c"))
        {
                return 1;
        }
        else
        {
                return 0;
        }
}

void findAllDirs(const char *path)
{
        DIR *dp;
        struct dirent *entry;
        struct stat statbuf;

        if ((dp = opendir(path)) == NULL)
        {
                fprintf(stderr, "The path %s is wrong!\n", path);
                return;
        }

        chdir(path);
        while ((entry = readdir(dp)) != NULL)
        {
                lstat(entry->d_name, &statbuf);

                if (!strcmp(".", entry->d_name) || !strcmp("..", entry->d_name))
                        continue;

                if (S_ISDIR(statbuf.st_mode))
                {
                        findAllDirs(entry->d_name);
                }
                else
                {
                        if (isCode(entry->d_name))
                        {
                                total += countLines(entry->d_name);
                        }
                }
        }

        chdir("..");
        closedir(dp);
}

int main()
{
        char path[MAX] = ".";

        printf("计算中...\n");

        findAllDirs(path);

        printf("目前你总共写了 %ld 行代码!\n\n", total);

        return 0;
}

注:将此程序放在你所有练习的程序的总的目录下

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值