unix下more命令的简单实现:
#include <stdio.h> #define PAGELEN 24 #define LINELEN 512 int do_more(FILE * file); int see_more(FILE * file); int main(int argc,char * argv[]) { FILE * fp; if(argc == 1) do_more(stdin); else { int argv_index = 1; while(argc > 1) { if((fp = fopen(argv[argv_index],"r")) == NULL) exit(1); do_more(fp); fclose(fp); argv_index++; argc--; } } return 0; } int do_more(FILE * fp) { char buffer[LINELEN]; int number_of_lines = 0; int reply; FILE * ftty; ftty = fopen("/dev/tty","r"); if(ftty == NULL) exit(1); while(fgets(buffer,LINELEN,fp)) { if(number_of_lines == PAGELEN) { fputs(buffer,stdout); reply = see_more(ftty); if(reply == 0) break; if(reply == 1) number_of_lines = 0; //if(reply == 2) // number_of_lines--; } else { number_of_lines++; fputs(buffer,stdout); } } } int see_more(FILE * fp) { char c; printf("enter your command(q space or enter):"); while((c = getc(stdin)) != EOF) { if(c == 'q')//按q退出 return 0; if(c == ' ') return 1;//按空格显示下一页 if(c == 'n') return 2;//按n显示下一行 } return 3; }
时间: 2024-10-14 08:09:10