C/C++统计文件里面 中文 字母 数字 空格 行数

统计文件里面 中文 字母 数字 空格 行数

  1. 中文识别,我的电脑中文占用3个字节,都是小于0
  2. 网上查询,中文占用2个字节
  3. 下面代码实现了目录文件遍历

直接上代码:

#if 1
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
#include<string>
#include<io.h>   //遍历目录需要的

using namespace std;

struct fileInfo
{
	int wordsNum = 0; //中文个数
	int letterNum = 0;//字母个数
	int mathNum = 0; //数字个数
	int spaceNum = 0;//空格数量
	int LineNum = 0; //行数
};
//判断是否为数字
bool isNum(char str)
{
	if (str >= '0' && str <= '9')
	{
		return true;
	}
	return false;
}
//判断是否为字母
bool isStr(char str)
{
	if (str >= 'A' && str <= 'z')
	{
		return true;
	}
	return false;
}
//判断是不是空格
bool isSpace(char str)
{
	if (str == ' ')
	{
		return true;
	}
	return false;
}
//判断中文
bool isChainese(char str)
{
	//内存里面的数都是小于0的
	if (str < 0)
	{
		return true;
	}
	return false;
}
//计算一个文件
void mainFanc(const char *testfile)
{
	//int a = strlen(testfile);
	//if (testfile[a - 2] == '.')
	//{
	//	return;
	//}
	fileInfo info;
	//char filePath[256]; //文件路径
	//testfile = "C:/Users/10110/Desktop/1/2.txt";
	//cout << "输入文件路径: ";
	//cin >> filePath;

	fstream file;
	//打开文件
	file.open(testfile, ios::in);
	//判断文件是否被打开
	if (!file.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}
	char str[256];
	//int pos = file.tellp();
	//cout << "输出流指针位置:" << pos << endl;
	while(!file.eof())
	{
		file.getline(str, 256);
		for (int i = 0; i < strlen(str); i++)
		{
			if (isNum(str[i]))
			{
				info.mathNum++; //统计数字个数
			}
			if (isStr(str[i]))
			{
				info.letterNum++;//统计字母个数
			}
			if (isSpace(str[i]))
			{
				info.spaceNum++;//统计空格个数
			}
			if (isChainese(str[i]))
			{
				i +=2;  //中文占用两个字节 ,我的电脑上面一个汉字占用3字节
				info.wordsNum++; //统计中文个数
			}
		}
		info.LineNum++;//统计行数
	}

	cout << "中文个数;" << info.wordsNum << endl;
	cout << "字母个数:" << info.letterNum << endl;
	cout << "数字个数:" << info.mathNum << endl;
	cout << "空格个数:" << info.spaceNum << endl;
	cout << "行数:" << info.LineNum << endl;
	return;
}

int main(void)
{
	//遍历目标文件路径
	string path;
	//cout << "输入反斜杠/" << endl;
	cout << "输入要遍历计算的文件路径:";
	getline(cin,path); //按行读取,不忽略空格
	string pathFull;
	pathFull = path + "\\*";
	//cout << path << endl;
	//cout << pathFull << endl;
	//"C:\\Program Files\\*";	
	struct _finddata_t fInfo;  //用来储存文件的各种信息的结构提
	long handle; //_findfirst返回long ,用于查找句柄
	handle = _findfirst(pathFull.c_str(), &fInfo);
	if (handle == -1)
	{
		cout << "遍历文件失败!" << endl;
	}
	string newPath;
	path += "\\";
	int num = -2;
	do 
	{
		cout << "第" << ++num << "个文件:  ";
		cout << fInfo.name << endl;
		//转换成绝对路径
		newPath = path + fInfo.name;
		//cout << fullPath.c_str() << endl;
		//cout << newPath.c_str() << endl;
		mainFanc(newPath.c_str());
	} while(!_findnext(handle,&fInfo));

	system("pause");
	return EXIT_SUCCESS;
}

#endif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值