more命令简单实现

1090阅读 0评论2014-04-16 do_my_heart
分类:C/C++


点击(此处)折叠或打开

  1. //more命令粗略实现

  2. #include<stdio.h>
  3. #include<stdlib.h>

  4. #define LINELEN    512
  5. #define    PAGELEN    24

  6. void do_more(FILE *fp);
  7. int see_more(FILE *cmd);

  8. int main(int argc,char *argv[])
  9. {
  10.     if(argc == 1)
  11.         do_more(stdin);
  12.     else
  13.     {
  14.         system( "stty -F /dev/tty cbreak" ); //打开/dev/tty作为输入终端,并且控制属性为不用回车
  15.         while(--argc)
  16.         {
  17.             FILE *fp;
  18.             if( (fp = fopen( *++argv,"r" )) != NULL )
  19.             {
  20.                 do_more(fp);
  21.                 fclose(fp);
  22.             }
  23.             else
  24.             {
  25.                 printf("open %s failed",*argv);
  26.                 exit(1);
  27.             }
  28.         }
  29.            system( "stty -F /dev/tty -cbreak" ); //恢复终端属性为需要回车
  30.     }
  31.     
  32.     return 0;
  33. }


  34. void do_more(FILE *fp)
  35. {
  36.     char line[LINELEN];
  37.     int num_of_lines = 0;
  38.     int reply;
  39.     FILE *fp_tty;

  40.     if( (fp_tty = fopen("/dev/tty","r")) == NULL )
  41.     {
  42.         puts("open /dev/tty failed");
  43.         exit(1);
  44.     }
  45.     
  46.     while( fgets(line,LINELEN,fp) )
  47.     {
  48.         if(num_of_lines == PAGELEN)
  49.         {
  50.             reply = see_more(fp_tty);
  51.             if(reply == 0)//键盘输入q退出
  52.                 break;
  53.             num_of_lines -= reply;
  54.         }
  55.         if( fputs(line,stdout) == EOF)
  56.             exit(1);
  57.         ++num_of_lines;
  58.     }
  59. }

  60. int see_more(FILE *cmd)
  61. {
  62.     int ch;
  63.     printf("\033[7m more ? \033[m");//反白字体
  64.     
  65.     while( (ch = getc(cmd)) != EOF )
  66.     {
  67.         if(ch == 'q')//退出
  68.             return 0;
  69.         if(ch == '\n')//下一行
  70.             return 1;
  71.         if(ch == ' ')//下一页
  72.             return PAGELEN;
  73.     }
  74.     return 0;
  75. }

上一篇:容易混淆的const
下一篇:who命令简单实现