已有文本文件,统计文件中字符出现的次数并输出

统计文件中字符出现的次数并输出

#include
#include
#include
#define N 100

typedef struct ch {
char a; //字符值
int num; //次数
struct ch* next;
}Ch; //定义结构体

struct ch* tongji(char[], Ch*); //统计字符次数并插入链表的函数
void printc(Ch*); //输出

int main()
{
FILE* fp;
char a[N];
int i = 0;
char c;
if ((fp = fopen(“D:\c\test.txt”, “r”)) == NULL)
{
printf(“cannot open this file”);
exit(0);
}
c = fgetc(fp);
while (!feof(fp))
{
a[i++] = c;
c = fgetc(fp);
printf("%c", c);
}
a[i] = ‘\0’;

Ch* p, * q;
q=p = (Ch*)malloc(sizeof(Ch));
if (!p)
	exit(0);
p->next = NULL;
q = tongji(a, p);
printc(q);

return 0;

}

Ch* tongji(char a[], Chhead) {
int i = 0;
Ch
p, * q;

for (i; a[i] != '\0'; i++)
{
	p = head;
	while (p->next)
	{
		if (p->next->a == a[i])
		{
			p->next->num++;
			break;
		}
		else
			p = p->next;
	}
		if (p->next == NULL)
		{
			q = (Ch*)malloc(sizeof(Ch));
			if (!q)
				exit(0);
			p->next = q;
			q->a = a[i];
			q->next = NULL;
			q->num = 1;
		}

	}
return head;

}
void printc(Ch* head)
{
Ch* p = head;
while (p->next)
{
printf("%5c %5d\n", p->next->a, p->next->num);
p = p->next;
}
}
已有文本文件,统计文件中字符出现的次数并输出_第1张图片

你可能感兴趣的:(已有文本文件,统计文件中字符出现的次数并输出)