Linux 下 more命令 的實現

$ vi more01.c

新建一個C文件

編輯程序

/**
* read and print 24 lines then pause for a few special commandv
*/
#include<stdio.h>
#define PAGELEN 24
#define LINELEN 512

void do_more(FILE *fp );
int see_more(FILE *cmd);

int main(int ac, char *av[] )
{
    FILE *fp;
    if(ac == 1)
    {
        do_more(stdin);
    }
    else
    {
        while(--ac)
        {
            if( (fp = fopen(* ++av, "r")) != NULL )
            {
                do_more( fp );
                fclose( fp );
            }
            else
            { 
                exit(1);
            }
            return 0;
        }
    }
}
/**
* read PAGELEN lines, then call see_more() for further instructtions
*/
void do_more( FILE *fp )
{
    char line[LINELEN] ;
    int  num_of_lines = 0;
    int  see_more(FILE *), reply;
    FILE *fp_tty;
    fp_tty = fopen("/dev/tty", "r");   // NEW:cmd stream
    while( fgets(line, LINELEN, fp) )  // more input
    {
        if(num_of_lines == PAGELEN ) // full screen?
        {
            reply = see_more( fp_tty ); //pass FILE
            if(reply == 0)           // n:done
                break;
            num_of_lines -= reply;   // reset count
        }
        if(fputs(line, stdout) == EOF)// show line
            exit(1);                  // or die
        num_of_lines++;               // count it
    }
}
/**
* print message, wait for response , return # of lines to advance
* q means no, spance means yes, CR means one line
*/
int see_more(FILE *cmd)
{
    int c;
    printf("\033[7m more? \033[m");
    while( (c = getc(cmd) ) != EOF ) // get response
    {
        if( c == 'q' )
             return 0;
        if( c == ' ')
             return PAGELEN;
        if( c == '\n' )
             return 1;
    }
    return 0;
}


編譯

$ gcc more01.c -o more01

執行以打開 more01.c爲例

$ ./more01 more01.c

可以每頁顯示24行。

末尾提示符【more?】

輸入q 或 空格退出。


參考《Unix/Linux編程實踐教程》



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章