自己动手写shell命令之more
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; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。