首页 > 代码库 > linux编程more命令的简单实现

linux编程more命令的简单实现

more 命令有三种用法:

1.more filename

2.command | more

3.more < filename

本例中在使用时要用./more_1执行也可以将more_1拷贝到/bin文件下执行,相当于添加了一条新的命令

more_1.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LINE_LENGTH 512
#define PAGE_LENGTH 24

int see_more(FILE* fp_cmd)
{
    if(fp_cmd == NULL)
        printf("error stop\n");
    char ch;
    printf("\033[7m more? \033[m");//vt100编程,详细参照网上
    while((ch = getc(fp_cmd)) != NULL) // 从终端读取
    {
        if(ch =='q')
            return 0;
        if(ch == ' ')
            return PAGE_LENGTH;;
        if(ch == '\n')
            return 1;
    }
    return 0;

}

void do_more(FILE* fp)
{
    int line_num = 0;
    char line_buf[LINE_LENGTH];
    int reply;
    FILE* fp_tty;
    if((fp_tty = fopen("/dev/tty","r")) == NULL) //括号使用,没有扩起来会出错
        perror("open tty error!\n");
    while(fgets(line_buf,LINE_LENGTH,fp))
        {
            if(line_num == PAGE_LENGTH)
            {
                reply = see_more(fp_tty);
                if(reply == 0)
                    break;
                if(reply == PAGE_LENGTH)
                    line_num = 0;
                if(reply == 1)
                    line_num --;
            }
            if(fputs(line_buf,stdout) == EOF)
                exit(-1);
            line_num++;
        }
    fclose(fp_tty);
}

int main(int argc,char* argv[])
{
    FILE* fp;
    if(argc == 1)
    {
        printf("usage: more [-dflpcsu] [+linenum | +/pattern] name1 name2 ...\n");

        exit(0);
    }
    else
        {
            while(--argc)
            {
                fp = fopen(* ++argv,"r");
                if(fp != NULL)
                {
                    do_more(fp);
                    fclose(fp);
                }
                else
                    perror("open eror!\n");
            }
        }
}



遗留问题:反白显示随着案件输入跳动显示

   百分比显示

  要按回车键执行

稍后再做完善

linux编程more命令的简单实现