打开文件的函数使用C自带的函数
FILE* fopen(char* path,char *r); 成功返回FIEL指针
读取文件记录的函数 fgets(buf,counts,fp); 成功返回实践读取的字数
设置客户端的终端控制,如输入空格换屏,不要回显,当字符处理等
使用 termios.h头函数
struct termios info;
tcgetattr(0,&info) ;读取终端设置,失败返回-1
tcsetattr(0,TCSANOW,&info); 设置终端设置,失败返回-1,TCSANOW可以设置终端立即相应
屏蔽终端的中断信号SIGINT,使在按下ctrl - c 时退出并且能够恢复终端的设置
信号控制使用signal.h头函数
signal(SIGINT,fun*);SIGQUIT,SIGIO等
此程序参考 unix/linux 编程实签教程
#include
<
stdio.h
>
#include
<
termios.h
>
#include
<
signal.h
>
#define
PAGELINE 24
#define
LINELEN 256
void
do_more(FILE
*
);
int
see_more(FILE
*
);
void
set_tty_mode();
void
reset_tty(
int
flag);
void
ctrl_c_hander();
int
main(
int
ac,
char
*
av[])
{
FILE
*
fp;
reset_tty(
0
);
set_tty_mode();
signal(SIGINT,ctrl_c_hander);
if
(ac
==
1
)
//
equal is command self
do_more(stdin);
else
while
(
--
ac)
{
if
((fp
=
fopen(
*++
av,
"
r
"
))
!=
NULL)
{
do_more(fp);
fclose(fp);
}
else
{
reset_tty(
1
);
return
-
1
;
}
}
reset_tty(
1
);
return
0
;
}
void
do_more(FILE
*
fp)
{
char
line[LINELEN];
int
readline
=
0
,reply;
FILE
*
ttyfp;
if
((ttyfp
=
fopen(
"
/dev/tty
"
,
"
r
"
))
==
NULL)
exit(
1
);
while
(fgets(line,LINELEN,fp))
//
return NULL is error
{
if
(readline
==
PAGELINE)
{
reply
=
see_more(ttyfp);
if
(reply
==
0
)
break
;
else
readline
-=
reply;
}
if
(fputs(line,stdout)
==
EOF)
//
return EOF is error
exit(
1
);
readline
++
;
}
}
int
see_more(FILE
*
ttyfp)
{
char
c;
printf(
"
\033[7m more? \033[m
"
);
while
((c
=
getc(ttyfp))
!=
EOF)
//
return EOF is error ,from tty
{
if
(c
==
'
q
'
)
return
0
;
if
(c
==
'
'
)
return
PAGELINE;
if
(c
==
'
\n
'
)
return
1
;
}
return
0
;
}
void
set_tty_mode()
{
struct
termios setting;
tcgetattr(
0
,
&
setting);
setting.c_lflag
&=
~
ECHO;
setting.c_lflag
&=
~
ICANON;
setting.c_cc[VMIN]
=
1
;
tcsetattr(
0
,TCSANOW,
&
setting);
}
void
reset_tty(
int
flag)
//
if flag=1 reset tty. flag=0 save tty mode
{
static
struct
termios info;
static
int
reset
=
0
;
if
(flag
==
0
)
{
tcgetattr(
0
,
&
info);
reset
=
1
;
}
else
if
(reset
==
1
)
{
tcsetattr(
0
,TCSANOW,
&
info);
}
}
void
ctrl_c_hander()
{
reset_tty(
1
);
exit(
1
);
}