这是一个 C 语言程序,包含了头文件 <unistd.h><fcntl.h><errno.h><string.h><stdlib.h>。程序的功能是从标准输入设备 (tty) 读取数据,如果读取失败,则每隔 6 秒输出一次消息 'try again',共尝试 5 次,如果还是无法读取数据,则输出消息 'timeout'。如果成功读取数据,则输出读取到的数据,并在屏幕上输出一个由星号组成的等腰三角形。程序的主要流程如下:

  1. 打开标准输入设备 /dev/tty,并设置为非阻塞模式。
  2. 尝试读取数据,如果读取失败,则判断是否是 EAGAIN 错误(表示设备当前没有数据可读),如果是,则等待 6 秒并输出 'try again' 消息,然后重试读取,最多重试 5 次。
  3. 如果读取成功,则输出读取到的数据,并在屏幕上输出一个由星号组成的等腰三角形。
  4. 关闭标准输入设备,并退出程序。

需要注意的是,这个程序只能在类 Unix 系统上运行,因为它使用了 Unix 系统的系统调用和设备文件。

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#define MSG_TRY 'try again\n'
#define MSG_TIMEOUT 'timeout\n'

int main(void)
{
	char buf[10];
	int fd, n, i, j;
	fd = open("/dev/tty", O_RDONLY|O_NONBLOCK);
	if(fd<0) {
		perror("open /dev/tty");
		exit(1);
	}
	for(i=0; i<5; i++) {
		n = read(fd, buf, 10);
		if(n>=0)
			break;
		if(errno!=EAGAIN) {
			perror("read /dev/tty");
			exit(1);
		}
		sleep(6);
		write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));
	}
	if(i==5)
		write(STDOUT_FILENO, MSG_TIMEOUT, strlen(MSG_TIMEOUT));
	else
		write(STDOUT_FILENO, buf, n);
	     for(i=0;i<5;i++){
	        for(j=0;j<=i;j++)
	           printf("%2c",'*');
	        printf("\n");
	     }
	close(fd);
	return 0;
}
C 语言程序:从标准输入读取数据并输出三角形

原文地址: http://www.cveoy.top/t/topic/nsuE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录