Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

파일의 문자, 줄 및 단어 수를 계산하는 C 프로그램

<시간/>

파일은 디스크의 물리적 저장 위치이고 디렉토리는 파일을 구성하는 데 사용되는 논리적 경로입니다. 디렉토리 내에 파일이 있습니다.

파일에 대해 수행할 수 있는 세 가지 작업은 다음과 같습니다. -

  • 파일을 엽니다.
  • 파일 처리(읽기, 쓰기, 수정).
  • 파일을 저장하고 닫습니다.

예시

아래 주어진 예를 고려하십시오 -

  • 쓰기 모드에서 파일을 엽니다.
  • 파일에 명령문을 입력합니다.

입력 파일은 다음과 같습니다 -

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

출력 다음과 같습니다 -

Number of characters = 72

Total words = 13

Total lines = 3

프로그램

다음은 파일의 문자, 줄 및 단어 수를 계산하는 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;
}

출력

위의 프로그램을 실행하면 다음과 같은 결과가 나온다 -

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