首頁 > 運維 > linux運維 > 主體

使用c語言寫wc指令-統計字元數、單字數、行數

齐天大圣
發布: 2020-10-26 14:10:38
原創
4600 人瀏覽過

我們知道linux作業系統上有一個非常常用的指令,用來統計字元數、單字數、行數的wc指令。今天,我們來嘗試使用c語言來寫一個類似功能的程式(註:閱讀本文需要一定的c語言基礎)。

編寫該程式時,需要掌握兩個函數的用法,getchar()以及putchar()。

getchar用來從標準輸入讀取一個字符,而putchar則是向標準輸出列印一個字符。統計標準輸入字符數比較簡單,只要getchar函數還能讀入字符,統計字符數的變數就自增加1。統計行數也簡單,只要讀入的字元為換行符\n則將統計函數的變數自增加1。

這裡的主要困難在於如何統計單字的數量,這裡我的思路是,設定一個狀態變數IN_WORD,當讀入的字元是空白字元時(空格、水平製表符、換行符都為空白字元),IN_WORD值為0,統計的單字數目不變,當等到讀入一個非空白字元時,統計單字的數目加1,IN_WORD值為1,當該狀態值為1時,即使讀入了非空白字符,單字統計的數目也不變動。

下面,貼出程式碼

#include 
#include 

#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
登入後複製

可以看到,程式可以正常統計字元數、單字數以及行數。

以上是使用c語言寫wc指令-統計字元數、單字數、行數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡[email protected]
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!