- /dev/tty
/dev/tty是键盘和显示器的设备描述文件,向这个文件写相当于显示在屏幕上,向这个文件读相当于从键盘读取输入,即使程序用’<’和‘>’重定位了标准输入和输出,依然可以通过这个文件和终端交换数据。
more01.cpp:
/*more01.cpp - version 0.1 of more
read and print 24 lines then pause for a few special conmands
*/
#include <stdio.h>
#include <stdlib.h>
#define PAGELEN 24
#define LINELEN 512
void do_more(FILE *);
int see_more();
int main(int argc, char* argv[])
{
FILE *fp;
if(argc==1)
do_more(stdin);
else
{
while(argc--)
{
if((fp=fopen(*++argv,"r"))!=NULL)
{
do_more(fp);
fclose(fp);
}
else
{
exit(1);
}
}
}
exit(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 see_more(),reply;
while(fgets(line,LINELEN,fp)) //more input
{
if(num_of_lines==PAGELEN)
{
reply = see_more();
if(reply==0)
break;
num_of_lines -= reply;
}
if(fputs(line,stdout)==EOF)
exit(1);
num_of_lines++;
}
}
int see_more()
/*
*print message,wait for response,return # of lines to advance
*q means no, space means yes, CR means one lines
*/
{
int c;
printf("\033[7m more?\033[m");
while((c=getchar())!=EOF)
{
if(c=='q')
return 0;
if(c==' ')
return PAGELEN;
if(c=='\n')
return 1;
}
return 0;
}
more02.cpp
/* more02.cpp - version 0.2 of more
* read and print 24 lines then pause for a few specoal commands
* feature of version 0.2 : reads from /dev/tty for commands
*/
#include <stdio.h>
#include <stdlib.h>
#define PAGELEN 24
#define LINELEN 512
void do_more(FILE *fp);
int see_more(FILE *fp);
int main(int argc, char* argv[])
{
FILE *fp;
if(argc==1)
do_more(stdin);
else
{
while(--argc)
{
if((fp=fopen(*++argv,"r"))!=NULL)
{
do_more(fp);
fclose(fp);
}
else
exit(1);
}
}
exit(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 see_more(FILE*),reply;
FILE *fp_tty;
fp_tty = fopen("/dev/tty","r");
if(fp_tty==NULL)
exit(1);
while(fgets(line,LINELEN,fp))
{
if(num_of_lines==PAGELEN)
{
reply = see_more(fp_tty);
if(reply==0)
break;
num_of_lines -= reply;
}
if(fputs(line,stdout)==EOF)
exit(1);
num_of_lines++;
}
}
int see_more(FILE* cmd)
/*
*print message,wait for response,return # of lines to advance
*q means no, space means yes,CR means one line
*/
{
int c;
printf("\033[7m more? \033[m");
while((c=getc(cmd))!=EOF)
{
if(c=='q')
return 0;
if(c==' ')
return PAGELEN;
if(c=='\n')
return 1;
}
return 0;
}