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


本文摘自PHP中文网,作者齐天大圣,侵删。

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

编写该程序时,需要掌握两个函数的用法,getchar()以及putchar()。

getchar用来从标准输入中读取一个字符,而putchar则是向标准输出打印一个字符。统计标准输入字符数比较简单,只要getchar函数还能读入字符,统计字符数的变量就自增加1。统计行数也简单,只要读入的字符为换行符\n则将统计函数的变量自增加1。

这里的主要难点在于如何统计单词的数量,这里我的思路是,设定一个状态变量IN_WORD,当读入的字符是空白字符时(空格、水平制表符、换行符都为空白字符),IN_WORD值为0,统计的单词数目不变,当等到读入一个非空白字符时,统计单词的数目加1,IN_WORD值为1,当该状态值为1时,即使读入了非空白字符,单词统计的数目也不变动。

下面,贴出代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

#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。

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

1

2

3

4

5

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个单词,共五行。

1

2

# cat 1.txt | ./a.out

542 86 5

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

以上就是使用c语言编写wc命令――统计字符数、单词数、行数的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

linux中如何编译C语言

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

centos如何编译C语言代码

linux如何计算目录中的文件数

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

linux中如何编译C语言

linux如何计算目录中的文件数

更多相关阅读请进入《C语言》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...