$ 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编程实践教程》