【Linux开发习作】more命令的编写(1)

 作者:gnuhpc 
出处:http://www.cnblogs.com/gnuhpc/

/*
* =====================================================================================
*
* Filename: more01.c
*
* Description: A User Version of Command more
*
* Version: 1.0
* Created: 12/03/2008 06:36:56 PM
* Revision: none
* Compiler: gcc
*
* Author: Futuredaemon (BUPT),gnuhpc@gmail.com
* Company: BUPT_UNITED
*
* =====================================================================================
*/

#include <stdlib.h>
#include <stdio.h>


#define PAGELEN 24 /*The number of pape to be printed */
#define LINELEN 512 /*The length of Line to be printed */

void do_more(FILE *);
int see_more(FILE *);

int main ( int argc, char *argv[] )
{
FILE *fp; /* File Descriptor */
if ( argc ==1 ) /* If no files exist,use the keyboard */
do_more(stdin);
else
while(--argc)
if((fp=fopen(*++argv,"r"))!=NULL)
{
do_more(fp);
fclose(fp);
}
else
exit(1);
return EXIT_SUCCESS;
} /* ---------- end of function main ---------- */

void do_more(FILE *fp)
{
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))
{
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)
{
int c;
printf("/033[7m more? /033[m");
while((c=getc(cmd))!=EOF)
{
//printf("This is a test!");
if(c == 'q')
return 0;
if(c == ' ')
return PAGELEN;
if(c == '/n')
return 1;
}
return 0;
}
posted @ 2012-01-13 11:12  gnuhpc  阅读(582)  评论(0编辑  收藏  举报