标准输入究竟是什么?

What exactly is stdin?

我对标准输入的实现有点困惑。它到底是什么?它是一个指针吗?我尝试在 64 位机器上使用 sizeof 打印 stdin 的大小并得到 8。我什至在 %s 说明符中使用 *stdin 取消引用它并在输入流中获得未使用的字符(所有字符)。但是如果我在里面比较它的去引用值的话会报错。我知道它是一个输入流。但是它是如何实现的呢?

这是一个示例:

#include<stdio.h>
#include<stdlib.h>

int main(){
    
    char a[10];

    fgets(a,10,stdin);

    printf("a: %s",a);
    
    printf("\nstdin: %s",*stdin);

//if(*stdin=="foo"){
//    printf("True");
//}//Error: invalid operands to binary == (have 'FILE' and 'char *')//and casting to char * doesn't help

    printf("\nSize of stdin: %d\n",sizeof(stdin));

    if(stdin!=NULL){
        printf("This statement is always reached");//always printed even in when input is bigger than 10 chars and otherwise
    }
    

if(!feof(stdin)){
    printf("\nThis statement is also always reached");
}
}

当我输入

foobar1234567890

我得到结果:

a: foobar123

stdin: 4567890

Size of stdin: 8

This statement is always reached

This statement is also always reached

当我输入

foobar

我得到输出

a: foobar

stdin:

Size of stdin: 4

This statement is always reached

This statement is also always reached

我知道 stdin 是一种 FILE 指针,但我不是很清楚。谁能解释一下上面的输出?

stdin标准输入的缩写)是指向只能用这些操作的FILE类型的指针函数:

https://en.wikipedia.org/wiki/C_file_input/output

在大多数(如果不是全部)实现中,FILE 类型是一个具有整数文件描述符和字符缓冲区的结构,允许缓冲 I/O 操作。此文件描述符以只读模式打开,通常连接到终端、管道或文件。

还有stdout(标准输出)和stderr(标准错误),以写入模式打开。

它是 OS 支持的标准输入服务的抽象。它被建模为流。 Check GNU LibC definitions.

stdin 是一个 FILE * 类型的指针。该标准不限制超出此范围的实现,FILE 的详细信息完全取决于您的编译器。它甚至可能是不完整的类型(不透明)。

当然,尝试用 %s 打印 FILE 会导致未定义的行为(除非 FILEchar * 或类似的类型定义,几乎可以肯定是不是)。

stdin、stdout、stderr 是 3 个打开的文件供您的应用用作默认输入文件、输出文件和错误输出文件。

并且这 3 个文件在您的应用程序启动之前已由系统打开。文件描述为 1、2 和 3。

如果关闭(1),stdin 文件将被关闭。然后,如果您打开另一个文件,stdin 将指向新文件。

所有不带FD的输入API(scanf, get, ...)都是从输入文件中读取数据,不带FD的输出API都是把值放到stdout中。

因此,如果您关闭 (1),并打开一个 return 值为 1 的新文件,printf 会将值放入您的文件。

typedef struct _IO_FILE FILE;
extern struct _IO_FILE *stdin;

所以它是一个指向 FILE 的指针。

标准说:

7.21 Input/output

stderr
stdin
stdout
which are expressions of type ‘‘pointer to FILE’’ that point to the FILE objects
associated, respectively, with the standard error, input, and output streams.