/*
* ============================================================================
*
* Filename: avrWordLens.c
*
* Description: 개별과제 - 단어들의 평균 길이 구하는 프로그램
*
* Version: 1.0
* Created: 01/07/09 21:05:18
* Revision: none
* Compiler: gcc
*
* Author: Kyungwook, Park, [email protected]
*
* ============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORD_LEN 80
/*
* === FUNCTION ==============================================================
* Name: search
* Description: 단어를 검색해 존재 유무를 리턴한다.(0: 없음, 1: 있음)
* ============================================================================
*/
int search(char** set, int* wordCnt, char* keyword) {
int results, i;
for (results = 1, i = 0; i < *wordCnt && results; i++)
results = strcmp(set[i], keyword);
return (results == 0) ? 1 : 0;
}
/*
* === FUNCTION ============================================================== * Name: load_words
* Description: 파일을 읽어와 단어 사전을 구축한다.
*
* Returns: 양수 - 단어 개수
* 0 - 단어가 존재하지 않은 빈파일이거나 파일을 열 수 없는 상태
* ============================================================================
*/
int load_words(char* fp_file_name, char*** set) {
FILE * fp; /* input-file pointer */
char tmpWord[WORD_LEN];/* 임시 단어를 위한 공간 */
int wordIdx = 0; /* 중복을 제외한 전체 단어 개수 */
int tmpWordLen = 0; /* 임시 단어의 길이 */
int arraySize = 0; /* 할당한 최대 크기 */
fp = fopen(fp_file_name, "r");
if (fp == NULL) {
return 0;
}
while (fscanf(fp, "%s", tmpWord) != EOF) /* 중복을 포함한 Word 총 개수 */
++(arraySize);
*set = (char**)malloc(sizeof(char*) * (arraySize)); /* 최대 개수만큼 동적 할당 */
rewind(fp);
while (fscanf(fp, "%s", tmpWord) != EOF) { /* 중복을 포함한 Word 총 개수 */
if (search(*set, &wordIdx, tmpWord)) /* 리스트에 단어가 존재 하면 넣지 않는다. */
continue;
tmpWordLen = strlen(tmpWord) + 1; /* 임시 문자열의 NULL 문자를 포함한 길이 */
(*set)[wordIdx] = (char*)malloc(sizeof(char) * tmpWordLen); /* 문자열을 위한 공간 할당 */
strcpy((*set)[wordIdx++], tmpWord); /* 문자열 복사 */
}
if (fclose(fp) == EOF) { /* close input file */
return 0;
}
return wordIdx; /* 시작 주소 리턴 */
}
void results(char** set, int totalWord) {
int i;
int sumWordLength = 0; /* 전체 단어 길이의 합 */
int tmpWordLength = 0;
for (i = 0; i < totalWord; i++) {
tmpWordLength = strlen(set[i]); /* 단어의 길이 */
sumWordLength += tmpWordLength; /* 단어 길이의 합 */
printf("%6d 번째 단어 : %-30s 단어길이 : %-6d\n",
i + 1, /* 단어의 위치 */
set[i], /* 단어 */
tmpWordLength); /* 단어의 길이 */
}
printf(" # 전체 단어의 개수 : %-6d\t 평균 단어 길이 %-6d\n\n",
totalWord, /* 전체 단어 개수 */
sumWordLength / totalWord); /* 평균 단어 길이 */
}
int main() {
char** wordList; /* 단어 공간을 위한 변수 */
char fileName[WORD_LEN]; /* 파일 이름을 위한 변수 */
int wordCnt = 0; /* 실제 단어 개수 */
printf("# 파일명을 입력하세요. 파일 내 단어들의 평균 길이를 알려드립니다.\n"); printf("\n- 파일명 > ");
scanf("%s", fileName);
wordCnt = load_words(fileName, &wordList); /* 단어를 불러와 개수를 리턴 */
if (wordCnt) /* 파일 속에 단어가 존재하면 */
results(wordList, wordCnt); /* 결과를 출력한다. */
else
printf("# 단어가 존재하지 않은 파일입니다! \n\n");
printf("# 프로그램을 종료합니다.\n");
return 0;
}