#include <stdio.h>
#include <stdlib.h>
#define PAGELEN 24
#define LINELEN 512
void do_more(FILE *); //将数据输出到屏幕
int see_more(FILE *); //接受用户输入
int main(int argc, char **argv){
FILE *fp;
if(argc==1) //不带文件参数就把输入打印出来
do_more(stdin);
else
{
while(--argc) //逐个打印文件
{
if((fp=fopen(*++argv,"r"))!=NULL){ //fopen "r"只读打开文件。 成功,返回非空的File*指针
do_more(fp);
fclose(fp); //关闭文件流
}
else{
printf("Errro: no such file.\n"); //fopen失败,返回NULL
exit(1); //退出,返回异常
}
}
}
return 0; //读完所有文件后,return 0
}
void do_more(FILE *fp)
/*
*read PAGELEN lines, then call see_more() for further instructions.
*/
{
char line[LINELEN];
int num_of_lines = 0;
int reply;
FILE *fp_tty;
fp_tty = fopen( "/dev/tty","r"); //从控制终端打开
if( fp_tty == NULL )
exit(1);
while( fgets(line,LINELEN,fp) ){ //从fp中读取LINELEN-1个字符,写到line指向的字符串中
if(num_of_lines == PAGELEN){ //输出满24行后,调用see_more
reply = see_more(fp_tty);
if( reply == 0 )
break;
num_of_lines -= reply;
}
if( fputs(line, stdout) == EOF ) //把line指向的字符串写入标准输出
exit(1);
num_of_lines++;
}
}
int see_more(FILE *cmd)
/*
*print message, wait for response
*q -> no ,space -> yes, CR -> one line
*/
{
int c;
printf("\033[7m more? \033[m");
while((c = getc(cmd)) != EOF)
{
if( c == 'q' )
return 0; //退出while
if( c == ' ' )
return PAGELEN; //再输出24行
if( c == '\n')
return 1; //输出1行
}
return 0;
}
《UNIX/LINUX编程实践教程》实例注释chapt1 - more2
最新推荐文章于 2021-06-09 11:00:35 发布