UNIX/LINUX编程实战教程读书笔记 ,开篇以more指令来进入:
more可以分页显示文件的内容,大部分的Unix系统都有文本文件“ /etc/termcap”,我使用的CentOS上也有,它经常被文本编辑器和游戏程序用到,那么用“ cat /etc/termcap”来查看的时候,通常一页是显示不完,太长了,这样more的价值出来了,使用“more ****”或者“cat **** | more”。
SO,它会显示文件第一屏的内容,在屏幕的底部,more用反白字体显示文件的百分比,这时如果按空格键,文件的下一屏内容会显示出来,如果按回车键,显示的则是下一行,如果输入“q”,结束显示,如果输入“h”,显示出来的是more的联机帮助。
本书在后面用它提及的方法来展示了自己编写more功能的代码,下面会把它贴上来 ,有个地方不会一样,就是觉得17面的程序中,因为它全局已经声明了一下“int see_more();”,我就在do_more()函数里把“int see_more()”给注释了。还是要多看看代码:
/*more01.c -- version 0.1 of more
*read and print 24 lines then pause for a few special commands
*/
#include <stdio.h>
#include <stdlib.h>
#define PAGELEN 24
#define LINELEN 512
void do_more(FILE *);
int see_more();
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 instructions
*/
void do_more(FILE *fp)
{
char line[LINELEN];
int num_of_lines = 0;
// int see_more(), reply;
int reply;
while(fgets(line,LINELEN,fp))
{
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++;
}
}
/*
*print message, wait for reponse, return # of lines to advance
*q means no, space means yes, CR means one line
*/
int see_more()
{
int c;
printf("\033[7m more?\033]");
while((c=getchar())!= EOF)
{
if(c == 'q')
return 0;
if(c == ' ')
return PAGELEN;
if(c == '\n')
return 1;
}
return 0;
}
下面一个是在以上面为基础而更完善的一点功能的程序:
/*more02.c -- version 0.2 of more
*read and print 24 lines then pause for a few special commands
*feature of version of 0.2: reads from /dev/tty for commands
*/
#include <stdio.h>
#include <stdlib.h>
#define PAGELEN 24
#define LINELEN 512
void do_more(FILE *);
int see_more(FILE *); //it is different from more01.c,
//"Note" stands for this difference.
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 instructions
*/
void do_more(FILE *fp)
{
char line[LINELEN];
int num_of_lines = 0;
// int see_more(), reply;
int reply;
FILE *fp_tty; //Note
fp_tty = fopen("/dev/tty","r"); //Note
if(fp_tty == NULL) //Note
exit(1); //Note
while(fgets(line,LINELEN,fp))
{
if(num_of_lines == PAGELEN)
{
reply = see_more(fp_tty); //Note
if(reply == 0)
break;
num_of_lines -= reply;
}
if(fputs(line,stdout) == EOF)
exit(1);
num_of_lines++;
}
}
/*
*print message, wait for reponse, return # of lines to advance
*q means no, space means yes, CR means one line
*/
int see_more(FILE *cmd) //Note
{
int c;
printf("\033[7m more? \033[m");
while((c=getc(cmd))!= EOF) //Note
{
if(c == 'q')
return 0;
if(c == ' ')
return PAGELEN;
if(c == '\n')
return 1;
}
return 0;
}
本书后面还留了点问题,可以更加完善后就和系统的more指令完成的功能一样了。后面会通过学习来解决它的。先到这样。