C程序计算文件中的字符,行和单词数

文件是磁盘上的物理存储位置,目录是用于组织文件的逻辑路径。文件存在于目录中。

我们可以对文件执行的三个操作如下 -

  • 打开一个文件。

  • 处理文件(读、写、修改)。

  • 保存并关闭文件。

示例

考虑下面给出的例子 -

  • 以写入模式打开文件。

  • 在文件中输入语句。

输入文件内容如下-

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

输出是如下-

Number of characters = 72Total words = 13Total 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 thetext.presscntrl Z:\n");
   while((ch = getchar())!=EOF){
      putc(ch,file);
   }
   fclose(file);
   printf("输入源文件路径: ");
   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 thetext.presscntrl Z:
Hi welcome to nhooo.com
C programming Articles
Best tutorial In the world
Try to have look on it
All The Best
^Z
输入源文件路径: counting.txt

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