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
广告