《C语言接口与实现》实验——表(WF)

该程序是《C语言接口与实现》书中P87页中wf示例源码:在下载:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include "include/atom.h"
#include "include/table.h"
#include "include/mem.h"
#include <string.h>
#include <assert.h>

void wf(char *, FILE *);
int first(int c);
int rest (int c);
int compare(const void *x, const void *y);
void vfree(const void *, void **, void *);

#pragma comment(lib, "libcii.lib")

int getword(FILE *fp, char *buf, int size,
			int first(int c), int rest(int c)) 
{
	int i = 0, c;
	assert(fp && buf && size > 1 && first && rest);
	c = getc(fp);
	for ( ; c != EOF; c = getc(fp))
		if (first(c)) {
			{
				if (i < size - 1)
					buf[i++] = c;
			}
			c = getc(fp);
			break;
		}
		for ( ; c != EOF && rest(c); c = getc(fp))
		{
			if (i < size - 1)
				buf[i++] = c;
		}
		if (i < size)
			buf[i] = '\0';
		else
			buf[size-1] = '\0';
		if (c != EOF)
			ungetc(c, fp);
		return i > 0;
}


int main(int argc, char *argv[]) 
{
	int i;
	for (i = 1; i < argc; i++) 
	{
		FILE *fp = fopen(argv[i], "r");
		if (fp == NULL) 
		{
			fprintf(stderr, "%s: can't open '%s' (%s)\n",
				argv[0], argv[i], strerror(errno));
			return EXIT_FAILURE;
		} else {
			wf(argv[i], fp);
			fclose(fp);
		}
	}
	if (argc == 1) wf(NULL, stdin);
	return EXIT_SUCCESS;
}
void wf(char *name, FILE *fp) 
{
	Table_T table = Table_new(0, NULL, NULL);
	char buf[128];
	while (getword(fp, buf, sizeof buf, first, rest))
	{
		const char *word;
		int i, *count;
		for (i = 0; buf[i] != '\0'; i++)
			buf[i] = tolower(buf[i]);
		word = Atom_string(buf);
		count = Table_get(table, word);
		if (count)
			(*count)++;
		else {
			NEW(count);
			*count = 1;
			Table_put(table, word, count);
		}
	}
	if (name)
		printf("%s:\n", name);
	{ int i;
	void **array = Table_toArray(table, NULL);
	qsort(array, Table_length(table), 2*sizeof (*array),
		compare);
	for (i = 0; array[i]; i += 2)
		printf("%d\t%s\n", *(int *)array[i+1],
		(char *)array[i]);
	FREE(array); }
	Table_map(table, vfree, NULL);
	Table_free(&table);
}
int first(int c) {
	return isalpha(c);
}
int rest(int c) {
	return isalpha(c) || c == '_';
}
int compare(const void *x, const void *y) {
	return strcmp(*(char **)x, *(char **)y);
}
void vfree(const void *key, void **count, void *cl) {
	FREE(*count);
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值