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:
");    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("
Unable to open file.
");       exit(EXIT_FAILURE);    }    characters = words = lines = 0;    while ((ch = fgetc(file)) != EOF){       characters++;    if (ch == '
' || ch == '\0')       lines++;    if (ch == ' ' || ch == '\t' || ch == '
' || ch == '\0')       words++;    }    if (characters > 0){       words++;       lines++;    }    printf("
");    printf("Total characters = %d
", characters);    printf("Total words = %d
", words);    printf("Total lines = %d
", 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

更新於:2021年8月31日

13K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.