본문 바로가기
C 언어

텍스트 파일의 단어를 세는 프로그램 (C 언어 사용)

by treeCoder 2020. 12. 31.

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가 프린트 된다.

 

댓글