c语言 统计文件的行数

这是我统计项目中代码的程序,分享给大家
大家可能会统计工程代码的行数,直接使用以下程序

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <errno.h>
#include <error.h>
#include <string.h>

#define error_exit(_errmsg_)	error(EXIT_FAILURE, errno, _errmsg_)

#define PATH_LEN	1024

int total;

int process_dir(void);
int process_file(const char *filename);

int main()
{
	process_dir();

	printf("total: %d\n", total);
	return 0;
}

int process_dir(void)
{
	DIR *dp = NULL;
	char *path = NULL;
	struct stat statbuff;
	struct dirent * dirbuf = NULL;
	int namlen = 0;

	path = getcwd(NULL, 0);

	if (NULL == (dp = opendir(path)))
		error_exit("opendir");

	while (NULL != (dirbuf = readdir(dp))) {
		/* get file stat */
		if (-1 == stat(dirbuf->d_name, &statbuff))
			error_exit(dirbuf->d_name);

		if ('.' == dirbuf->d_name[0])
			continue;
		if (S_ISDIR(statbuff.st_mode)) {
			/* if dir, then recursion */
			if (-1 == chdir(dirbuf->d_name))
				error_exit(dirbuf->d_name);
			process_dir();
		} else {
			/*regular file, comput line*/
			namlen = strlen(dirbuf->d_name);
			//这里可以添加其它文件
			if (strcmp(".c", dirbuf->d_name+namlen-2) 
					&& strcmp(".h", dirbuf->d_name+namlen-2)
					&& strcmp(".cpp", dirbuf->d_name+namlen-4)
					&& strcmp(".cxx", dirbuf->d_name+namlen-4)
					) 
				continue;
			namlen = process_file(dirbuf->d_name);

			if (namlen < 400) {
				printf("%-30s %d\n", dirbuf->d_name, namlen);
				total += namlen;
			}
		}
	}
	closedir(dp);
	chdir("..");
	return 0;
}

int process_file(const char *filename)
{
	FILE *fp = NULL;
	char tmp[1024];
	int line = 0;

	if (NULL == (fp = fopen(filename, "r")))
		error_exit(filename);
	
	while (NULL != fgets(tmp, 1024, fp))
		line ++;

	return line;
}

l

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

废人一枚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值