什么是“标准输入"? [英] What is “standard input”?

查看:29
本文介绍了什么是“标准输入"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是用 C 创建一个测试程序,该程序读取标准输入的内容,然后打印出来.

但我有点怀疑:什么是标准输入?

是我在键盘上输入的吗?这是我必须阅读的文件吗?

两者都有吗?

标准输出也是如此:它是控制台吗?一个文件?

解决方案

C 标准(例如 C99 或 C11)定义了标准 标头(在适当地 #include-d 它).请参阅 stdio(3) 手册页.然后你有 stdinstdoutstderr 文件句柄(指向一些 FILE 的指针,它是一种抽象数据类型).

stdin 与某些设备(例如键盘)相关的事实是特定于实现的.

您可以(但那将是不道德和/或低效的)实现 C 标准,例如一个人类奴隶的房间(这是不道德的,如果您使用效率低下的带薪工人),而不是使用计算机.通常,计算机会在某些操作系统的帮助下为您提供一些 C 标准的实现.>

您可能想知道,在 C 程序中,stdin 是键盘"还是从某个文件"重定向.不幸的是,AFAIK,没有 C99 标准的方式来知道这一点.

正如您所提到的,stdinstdoutstderr 应该在您的程序启动时可用(即在输入 main ....).因此,除非您 fclose stdin 流,否则您可以读取它(使用 getcharscanfgetlinefgetsfscanf ... 和朋友)无需任何事先关心(所以你不需要 fopen 它自己).

在 Linux 或大多数 Posix 系统上,您可以将其用作近似值 isatty(STDIN_FILENO) - 请参阅 isatty(3) 了解更多 - 测试 stdin 是否是"键盘"(通过测试它是否是某个 tty).另请参阅 &那个.

I was tasked with creating a test program in C that reads the contents of the standard input and then prints them.

But I have a little doubt: what is exactly standard input?

Is it what I type in the keyboard? Is it a file I have to read?

Both of them?

And the same goes for standard output: is it the console? a file?

解决方案

The C standard (e.g. C99 or C11) defines what should be expected from the standard <stdio.h> header (after having suitably #include-d it). See stdio(3) man page. Then you have the stdin and stdout and stderr file handles (pointers to some FILE which is an abstract data type).

The fact that stdin is related to some device (e.g. a keyboard) is implementation specific.

You could (but that would be unethical and/or inefficient) implement the C standard with e.g. a room of human slaves (that is unethical, if you use paid workers that would be just inefficient), instead of using a computer. Often, computers gives your some implementation of the C standard thru the help of some operating system.

You may want to know, inside your C program, if stdin is a "keyboard" or redirected from some "file". Unfortunately, AFAIK, there is no C99-standard way to know that.

As you mention, stdin, stdout and stderr should be available in your program at startup (i.e. after entering main ....). Hence, unless you fclose the stdin stream, you can read it (with getchar, scanf, getline, fgets, fscanf ... and friends) without any prior care (so you don't need to fopen it yourself).

On Linux or most Posix systems, you might use as an approximation isatty(STDIN_FILENO) - see isatty(3) for more - to test if stdin "is" the "keyboard" (by testing if it is some tty). See also this & that.

这篇关于什么是“标准输入"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆