看了APUE的IO部分后,可以实践一下,写个简陋的more命令
more能做什么
more会显示一个屏的内容,在左下角还显示了文件的百分比,如果按空格键,文件的下一屏辉县市,如果按回车则显示下一行内容,如果输入'q',结束现实。
more的基本用法
- more filename
- command | more
- more < filename
简单的实现方法
如下:
#include <stdio.h>
#include <stdlib.h>
#define PAGELEN 24 //页面行数
#define BUFLEN 1024 // 缓冲区大小
// 根据用户的输入来决定显示下一页还是下一行或是退出
int selectMore(FILE *fp)
{
int c = fgetc(fp);
if (c == 'q')
return 0;
if (c == '
')
return 1;
if (c == ' ')
return PAGELEN;
else
return 0;
}
int mainMore(FILE *fp)
{
// 缓冲区
char buf[BUFLEN];
// 记录已打印行数
int row = 0;
// 接受用户的选项q, ' ', '
'
int reply = 0;
// 从文件流获取一行
while (fgets(buf, BUFLEN, fp) != NULL)
{
// 首先判断是否已经打印24行
if (row == PAGELEN)
{
// 接受打印多少行
reply = selectMore(stdin);
// 不打印 退出
if (reply == 0)
{
exit(0);
}
// 打印一行 或 一页
else
{
row -= reply;
}
}
else
{
// 打印一行
fputs(buf, stdout);
row++;
}
}
}
int main(int argc, char *argv[])
{
FILE *fp = NULL;
if (argc == 1)
{
mainMore(stdin);
}
// 至少提供打印的文件1个
else
{
while ((fp = fopen(argv[--argc], "r")))
{
mainMore(fp);
fclose(fp);
}
}
exit(0);
}
总结
使用的时候,还是有些bug,比如敲入空格时,还需要按下会车才会显示下一页,还需要优化优化。