Computer >> 컴퓨터 >  >> 프로그래밍 >> C 프로그래밍

C 프로그램으로 파일의 문자, 줄, 단어 수 계산하기

파일(file)은 디스크에 존재하는 물리적인 저장 공간이며, 디렉터리(directory)는 파일을 체계적으로 정리하기 위한 논리적인 경로입니다. 하나의 파일은 반드시 어떤 디렉터리 안에 존재하게 됩니다.

파일에 대해 수행할 수 있는 기본 작업은 크게 세 가지입니다.

  • 파일 열기
  • 파일 처리(읽기, 쓰기, 수정)
  • 파일 저장 후 닫기

예제 소개

간단한 예제를 통해 살펴보겠습니다.

  • 쓰기 모드로 파일을 엽니다.
  • 파일에 문장을 입력합니다.

입력 파일의 내용은 다음과 같습니다.

Hi welcome to my world
This is C programming tutorial
From tutorials Point

출력 결과는 다음과 같습니다.

문자 수 = 72
총 단어 수 = 13
총 줄 수 = 3

C 프로그램 코드

다음은 파일 내 문자, 줄, 단어 수를 계산하는 C 프로그램입니다.

#include <stdio.h>
#include <stdlib.h>
int main(){
    FILE * file;
    char path[100];
    char ch;
    int characters, words, lines;
    file=fopen("counting.txt","w");
    printf("enter the text.press cntrl Z:\n");
    while((ch = getchar())!=EOF){
        putc(ch,file);
    }
    fclose(file);
    printf("Enter source file path: ");
    scanf("%s", path);
    file = fopen(path, "r");
    if (file == NULL){
        printf("\nUnable to open file.\n");
        exit(EXIT_FAILURE);
    }
    characters = words = lines = 0;
    while ((ch = fgetc(file)) != EOF){
        characters++;
        if (ch == '\n' || ch == '\0')
            lines++;
        if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
            words++;
    }
    if (characters > 0){
        words++;
        lines++;
    }
    printf("\n");
    printf("Total characters = %d\n", characters);
    printf("Total words = %d\n", words);
    printf("Total lines = %d\n", lines);
    fclose(file);
    return 0;
}

프로그램 동작 원리

이 프로그램은 다음과 같은 순서로 동작합니다.

  1. 먼저 쓰기 모드("w")로 counting.txt 파일을 연 뒤, 사용자가 Ctrl+Z(EOF)를 입력할 때까지 표준 입력으로 받은 텍스트를 파일에 기록합니다.
  2. 분석할 파일의 경로를 입력받아 읽기 모드("r")로 엽니다. 파일을 여는 데 실패하면 오류 메시지를 출력하고 프로그램을 종료합니다.
  3. fgetc() 함수로 파일을 한 글자씩 읽으며 문자 수를 셉니다. 개행 문자('\n')를 만나면 줄 수를, 공백·탭·개행 문자를 만나면 단어 수를 각각 증가시킵니다.
  4. 읽어 들인 문자가 하나라도 있다면 마지막 단어와 마지막 줄까지 포함되도록 words와 lines 값을 1씩 더해 보정합니다.

실행 결과

위 프로그램을 실행하면 다음과 같은 결과를 확인할 수 있습니다.

enter the text.press cntrl Z:
Hi welcome to Tutorials Point
C programming Articles
Best tutorial In the world
Try to have look on it
All The Best
^Z
Enter source file path: counting.txt

Total characters = 116
Total words = 23
Total lines = 6