[ create a new paste ] login | about

Link: http://codepad.org/FbzJn4nu    [ raw code | output | fork ]

C, pasted on Jun 22:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct Dictionary{
	struct Dictionary*next;

	char*			word;
}Dictionary;
static	void	init_dictionary(Dictionary* root){
	memset(root,0,sizeof(*root));
};
static	void	final_dictionary(Dictionary* root){
	Dictionary*	next = root->next;
	while(next){
		Dictionary*	cur = next;
		next = next->next;

		free(cur);
	}
	memset(root,0,sizeof(*root));
}
static	int	add_dictionary(Dictionary* root, const char* word){
	Dictionary*	cur = malloc(sizeof(Dictionary) + strlen(word)+1);
	if(!cur){
		return -1;
	}

	cur->word = (char*)(cur+1);
	strcpy(cur->word,word);

	cur->next = root->next;
	root->next = cur;

	return 0;
}
static	int		count_dictionary(Dictionary* root, const char* word){
	int	count = 0;

	Dictionary*	next = root->next;
	while(next){
		if(!strcmp(word,next->word)){
			count ++;
		}
		next = next->next;
	}
	return count;
}



int main(int argc, char** argv){
	Dictionary	root;
	init_dictionary(&root);

	{
		FILE*	fp;

		fp = fopen("input.txt","r");
		if(!fp){
			printf("Cannot found 'input.txt'!\n");
			return -1;
		}

		{
			char	buf[256];
			while ((fgets(buf,sizeof(buf),fp)) != NULL){
				int	len = strlen(buf);
				if(buf[len-1] == '\n'){
					buf[len-1] = '\0';
				}
				if(!strlen(buf)){
					continue;
				}

				if(add_dictionary(&root,buf)){
					fclose(fp);
					final_dictionary(&root);

					return -1;
				}
			}
		}

		fclose(fp);
	}

	{
		char	buf[256];
		printf("plese any word>");
		scanf("%s",buf);
		printf("%d\n",count_dictionary(&root,buf));
	}

	final_dictionary(&root);

	return 0;
}


Output:
1
2
3
Cannot found 'input.txt'!

Exited: ExitFailure 255


Create a new paste based on this one


Comments: