C 언어로 텍스트 파일의 단어를 세는 프로그램이다.
일단 아래의 파일을 wordCount.c 라는 파일에 저장하고 Compile한다.
#include <stdio.h>
int i;
char tmp[256];
int print(int *cnt ) {
tmp[--i] = 0x00; /* remvove last char and finish string */
/* in this logic Tab, NewLine, Space, EOF
are to be removed. */
if( i > 0 )
printf("%04d, %s\n", ++*cnt, tmp);
i = 0;
return 0;
}
int main( ) { int cnt = 0;
int c;
i = 0;
while( ( c = getchar() ) != EOF ) {
tmp[i++] = c;
if( c == 9 || /* If c is a Tab */
c == 10 || /* If c is a New Line */
c == 32 ) { /* if c is a Space */
print(&cnt);
}
}
tmp[i++] = c; /* add EOF char to the string,
so it can be removed in the print function */
print(&cnt);
return 0;
}
Compile이 되었다면. text.txt 라는 파일에 아래와 같이 입력하고 저장한다.
Hello, C!
C language is not easy to learn.
But I love C language.
사용 방법은 wordCount < test.text 라고 하면 된다.
실행 결과는 다음과 같이 14개의 word가 프린트 된다.

'C 언어' 카테고리의 다른 글
| 매크로함수를 활용한 프로그램 (0) | 2020.12.31 |
|---|---|
| 자료구조 연결 리스트 함수들 정리 (0) | 2020.12.31 |
| C 언어로 방정식의 해를 구하기 (Bisection method) (0) | 2020.12.31 |
| C언어로 현재 폴더의 모든 텍스파일 처리하기 (1) | 2020.12.31 |
| C언어를 이용하여 무작위로 사람 이름 만들기 (0) | 2020.12.18 |
댓글