统计文件里面 中文 字母 数字 空格 行数
- 中文识别,我的电脑中文占用3个字节,都是小于0
- 网上查询,中文占用2个字节
- 下面代码实现了目录文件遍历
直接上代码:
#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