#include <termios.h>
#include <unistd.h>
int getch()
{
struct termios tm,tm_old
int fd = STDIN_FILENO,c
setbuf(stdin,NULL)
if (tcgetattr(fd, &tm) < 0)
{
return -1
}
tm_old = tm
cfmakeraw(&tm)
if (tcsetattr(fd,TCSANOW, &tm) < 0)
{
return -1
}
c = fgetc(stdin)
if (tcsetattr(fd,TCSANOW,&tm_old) < 0)
{
return -1
}
return c
}
int main()
{
system("clear")
printf("按任意键退出。。。\n")
getch()
return 0
}
C语言中可以使用函数system()、getch()实现按键退出。
1、直接调用系统函数 system(“pause”):
system()会调用fork()产生子进程, 由子进程来调用/bin/sh-c string 来执行参数string 字符串所代表的命令, 此命令执行完后随即返回原调用的进程。
system(“pause”)可以实现冻结屏幕,便于观察程序的执行结果。
2、调用getch()函数:
此函数是一个不回显函数,当用户按下某个字符时,函数自动读取,无需按回车,需要include<conio.h>
扩展资料
一、使用getch函数设置退出
所在头文件:conio.h。
函数用途:从控制台读取一个字符,但不显示在屏幕上。
函数原型:intgetch(void)
返回值:读取的字符。
二、打开文件的操作通过标准库函数 fopen
函数 fopen 的第二个参数指定了文件的访问模式,访问模式决定了流所许可的输入和输出操作。对访问模式字符串的许可值有严格的限制。
该字符串的第一个字符只能为三种形式:r(read)、w(write)或者 a(append)。另可加字符b表示以二进制方式打开文件。