#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
bool isA2z(char c)
{
bool bl = true;
if(!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '-'))
{
bl = false;
}
return bl;
}
bool isword(char s[])
{
bool bl = true;
int i = 0;
for(i = 0; i < strlen(s); i++)
{
if(!isA2z(s[i]))
{
return false;
}
}
return bl;
}
bool format(char s[20])
{
bool bl = true;
int i = 0;
int j = 0;
char s_temp[20];
s_temp[0] = 127;
for(i = 0; i < strlen(s); i++)
{
if(isA2z(s[i]))
{
s_temp[j] = s[i];
j++;
}
}
if(s_temp[0] == 127)
{
return false;
}
s_temp[j] = '\0';
j = 0;
for(i = 0; i < strlen(s_temp); i++)
{
s[i] = s_temp[i];
j++;
}
s[j] = '\0';
return bl;
}
int main(void)
{
int k = 1;
printf("————————欢迎使用文本统计程序————————\n");
while (k)
{
FILE *fp;
FILE *fp_sort;
char word[20];
char filename[20];
int sort[27];
sort[26] = 0;
printf("请输入要统计的文件的文件名:\n");
scanf("%s", &filename);
int i = 0;
char filename_sort[20] = "a.txt";
printf("统计结果如下:\n");
for(i = 0; i < 26; i++)
{
sort[i] = 0;
filename_sort[0] = 'a' + i;
if((fp_sort = fopen(filename_sort, "w")) == NULL)
{
printf("Child file open error!\n");
exit(0);
}
if((fp = fopen(filename, "r")) == NULL)
{
printf("File open error!\n");
exit(0);
}
while (!feof(fp))
{
fscanf(fp, "%s", &word);
if(format(word))
{
if(word[0] == 'a' + i || word[0] == 'A' + i)
{
fputs(word, fp_sort);
fputs(" ", fp_sort);
sort[i]++;
sort[26]++;
}
}
}
fclose(fp_sort);
fclose(fp);
printf("以字母%c开头的单词共有%d个\n", 'a' + i, sort[i]);
}
printf("本文单词总数为%d个\n", sort[26]);
printf("输入数字0退出,输入其他数字继续统计下一篇\n");
scanf("%d", &k);
}
return 0;
}
这个是在linux下运行的版本