这是自己用C语言编写的一个more程序,主要用到了终端控制和C语言的控制符功能,源代码如下:
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
-
-
- #define PAGELEN 24
- #define LINELEN 80
-
- void do_more(FILE *);
- int get_more_cmd(FILE *);
-
- int read_size, total_size;
-
-
-
-
-
-
-
-
-
-
- int main( int argc , char **argv )
- {
- FILE *fp;
-
- if ( argc == 1 )
- do_more( stdin );
- else {
- system ("stty -F /dev/tty cbreak");
-
- while ( --argc )
- if ( (fp = fopen( *++argv , "r" )) != NULL )
- {
- do_more( fp ) ;
- fclose( fp );
- }
- else
- exit(1);
- system ("stty -F /dev/tty -cbreak");
- }
- return 0;
- }
-
- void do_more( FILE *fp )
- {
- char line[LINELEN];
- int num_of_lines = 0;
- int reply;
- FILE *fp_tty;
-
- if (fp != stdin) {
-
- fseek (fp, 0, SEEK_END);
- total_size = ftell (fp);
- fseek (fp, 0, SEEK_SET);
- }
-
- fp_tty = fopen( "/dev/tty", "r" );
- if ( fp_tty == NULL )
- exit(1);
-
- while ( fgets( line, LINELEN, fp ) ){
- read_size += strlen(line);
- if ( num_of_lines == PAGELEN ) {
- reply = get_more_cmd(fp_tty);
- if ( reply == 0 )
- break;
- num_of_lines -= reply;
- }
- if ( fputs( line, stdout ) == EOF )
- exit(1);
- num_of_lines++;
- }
- }
-
- int get_more_cmd(FILE *cmd)
-
- {
- int c;
-
- printf ("\033[7m - %d/%d - more? \033[0m", read_size, total_size);
-
- while( (c=getc(cmd)) != EOF )
- {
- if ( c == 'q' )
- {printf("\n");return 0;}
- if ( c == ' ' )
- {printf("\033[2J"); return PAGELEN;}
- if ( c == '\n' )
- {printf("\033[A\033[2K");return 1;}
- }
- return 0;
- }
命令结果如下:
./a.out more02.c
按空格键,翻到下一屏.
按回车键,显示下一行.
按q键退出.
(周立发) |