實(shí)現(xiàn)了命令more的基本功能,但還有如下缺陷:more的反白先是不能固定,不能顯示百分比,在輸入命令后必需按回車。
下面是代碼,在FC4上使用gcc 編譯通過。
??1?#include?<stdio.h>
??2?#include?<stdlib.h>
??3?
??4?#define?PAGELEN?24
??5?#define?LINELEN?512
??6?
??7?void?do_more(FILE?*);
??8?int?see_more();
??9?int?see_more(FILE?*);
?10?
?11?
?12?int?main(int?ac,?char?*av[])
?13?{
?14???FILE?*fp;
?15???
?16???if?(ac?==?1)
?17????????do_more(stdin);
?18???else
?19????????while(--ac)
?20????????????if((fp?=?fopen(*?++av,?"r"))?!=?NULL)
?21????????????{
?22??????????????do_more(fp);
?23??????????????fclose(fp);
?24????????????}
?25????????????else
?26??????????????exit(1);
?27??
?28????return?0;
?29?}
?30?
?31?void?do_more(FILE?*fp)
?32?/*
?33??*??read?PAGELEN?lines,?then?call?see_more()?for?further?instructions
?34??*/
?35?{
?36???char?line[LINELEN];
?37???int?num_of_lines?=?0;
?38???int?see_more(FILE?*),?reply;
?39???
?40???
?41???//?get?input?from?stardard?input?device
?42????/*
?43????FILE?*fp_tty;
?44????fp_tty?=?fopen("/dev/tty",?"r");
?45????if?(fp_tty?=?NULL)?
?46????????exit(1);*/
?47????
?48????FILE????*fp_tty;
?49?
?50?????fp_tty?=?fopen(?"/dev/tty",?"r"?);????????
?51?????if?(?fp_tty?==?NULL?)???????????????
?52?????????exit(1);???????????????????????????
?53?????????
?54???while?(fgets(line,?LINELEN,?fp))
?55???{
?56?????if?(?num_of_lines?==?PAGELEN)
?57?????{
?58???????//printf("\n======?\n");
?59???????//reply?=?see_more();
?60???????reply?=?see_more(fp_tty);
?61???????if?(reply?==?0)?break;
?62???????num_of_lines?-=?reply;
?63?????}
?64?????
?65?????if?(fputs(line,?stdout)?==?EOF)?
?66?????????exit(1);
?67?????
?68?????num_of_lines++;
?69?????
?70?????//printf("\n======?num_of_lines?=?%d?\n",?num_of_lines);
?71???}
?72?}
?73?
?74?int?see_more()
?75??/*
?76??*??print?message?,?wait?for?response,?return?#?of?lines?to?advance
?77??*??q?means?no,?space?means?yes,?CR?means?one?line.
?78??*/
?79?{
?80???int?c;
?81???printf("\033[7m?more??\033[m");
?82???while?(?(c?=?getchar())?!=?EOF)
?83???{
?84?????if?(?c?==?'q')??return?0;
?85?????if?(?c?==?'?')??return?PAGELEN;
?86?????if?(?c?==?'\n')?return?1;
?87???}
?88???
?89???return?0;
?90?}
?91?
?92?int?see_more(FILE?*cmd)
?93?{
?94???int?c;
?95???printf("\033[7m?more??\033[m");
?96???while?(?(c?=?getc(cmd))?!=?EOF)
?97???{
?98?????if?(?c?==?'q')??return?0;
?99?????if?(?c?==?'?')??return?PAGELEN;
100?????if?(?c?==?'\n')?return?1;
101???}
102???
103???return?0;
104?}
105?
有兩個(gè)子函數(shù),do_more()和see_more(),前者處理顯示,后者處理命令。
以后在進(jìn)行改進(jìn)。