使用c语言编写wc命令——统计字符数、单词数、行数

我们知道linux操作系统上有一个非常常用的命令,用来统计字符数、单词数以及行数的wc命令。今天,我们来尝试使用c语言来编写一个类似功能的程序(注:阅读本文需要一定的c语言基础)。

编写该程序时,需要掌握两个函数的用法,getchar()以及putchar()。getchar用来从标准输入中读取一个字符,而putchar则是向标准输出打印一个字符。统计标准输入字符数比较简单,只要getchar函数还能读入字符,统计字符数的变量就自增加1。统计行数也简单,只要读入的字符为换行符\n则将统计函数的变量自增加1。这里的主要难点在于如何统计单词的数量,这里我的思路是,设定一个状态变量IN_WORD,当读入的字符是空白字符时(空格、水平制表符、换行符都为空白字符),IN_WORD值为0,统计的单词数目不变,当等到读入一个非空白字符时,统计单词的数目加1,IN_WORD值为1,当该状态值为1时,即使读入了非空白字符,单词统计的数目也不变动。

下面,贴出代码

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

#define IN_WORD 1
#define OUT_WORD 0

void main (void)
{
    int nc,nw,nl;
    char c,word_flag;

    nc = nw = nl = 0;
    word_flag = OUT_WORD;

    while ((c = getchar()) != EOF) {
        nc ++;

        if (c == '\n') {
            nl ++;
        }

        if (!isspace(c) && word_flag == OUT_WORD) {
            nw ++;
            word_flag = IN_WORD;
        } else if (isspace(c) && word_flag == IN_WORD) {
            word_flag = OUT_WORD;
        } 
    }

    printf("%d\t%d\t%d\n", nc, nw, nl);
}

上述代码还是非常的简单的,nc,nw,nl三个变量分别来统计字符数、单词数以及行数。而word_flag是用来记录状态的,状态分为两种,IN_WORD以及OUT_WORD。

接下来,我们来测试下上述代码。下面是一段文本:

Product-minded engineers are developers with lots of interest in the product itself. 
They want to understand why decisions are made, how people use the product, and love to be involved in making product decisions.
They're someone who would likely make a good product manager if they ever decide to give up the joy of engineering. 
I've worked with many great product-minded engineers and consider myself to be this kind of developer. 
At companies building world-class products, product-minded engineers take teams to a new level of impact.

上述文本共有86个单词,共五行。

# cat 1.txt | ./a.out 
542 86  5

可以看到,该程序可以正常统计字符数、单词数以及行数。

3 Replies to “使用c语言编写wc命令——统计字符数、单词数、行数”

  1. I have recently started a web site, the info you offer on this web site has helped me tremendously. Thank you for all of your time & work. Brynne Heinrick Houlberg

发表评论

电子邮件地址不会被公开。 必填项已用*标注