c语言统计文件单词数

1、

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>

int main(void)
{
    int ch;
    char filename[128];
    
    FILE * fp;
    bool word = false;
    bool space = false;
    int words = 0;
    
    printf("please input the filename: ");
    scanf("%s", filename);
    
    fp = fopen(filename, "r");
    
    if(fp == NULL)
    {
        printf("file open failed.
");
        exit(1);    
    }    
    
    while((ch = fgetc(fp)) != EOF)
    {
        putchar(ch);
        if(!isspace(ch))
            word = true;
        if(isspace(ch))
            space = true;
        if(word && space)
        {
            words++;
            word = false;
            space = false;
        }
        if(!word && space)
        {
            space = false;    
        } 
    }
    if(word)
        words++;
    printf("
words: %d.
", words);
        
    return 0;
} 

原文地址:https://www.cnblogs.com/liujiaxin2018/p/15202944.html