选择java 进入自由开放的国度

随笔 - 49, 文章 - 3, 评论 - 154, 引用 - 1
数据加载中……

linux中命令more的实现

实现了命令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 == 0break;
 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 
有两个子函数,do_more()和see_more(),前者处理显示,后者处理命令。

以后在进行改进。

posted on 2006-03-27 08:36 soochow_hhb 以java论成败 以架构论英雄 阅读(1148) 评论(0)  编辑  收藏 所属分类: Reading


只有注册用户登录后才能发表评论。


网站导航: