什么是stdin?

时间:2017-06-07 22:37:43

标签: c gcc stdin

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

以下是一个示例:

#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

     

标准差的大小:8

     

始终达到此声明

     

也始终达到此声明

当我输入

  

foobar的

我得到了输出

  

a:foobar

     

标准输入:

     

标准差的大小:4

     

始终达到此声明

     

也始终达到此声明

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

5 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:4)

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

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

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

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

答案 2 :(得分:1)

它是操作系统支持的标准输入服务的抽象。它被建模为流。 Check GNU LibC definitions

答案 3 :(得分:1)

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

在应用启动之前,系统已打开这3个文件。文件描述分别为1,2和3。

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

没有FD的所有输入API(scanf,get,...)都是从输入文件读取数据,没有FD的输出API将值放入stdout。

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

答案 4 :(得分:1)

typedef struct _IO_FILE FILE;
extern struct _IO_FILE *stdin;

所以它是指向FILE的指针。

标准说:

  

7.21输入/输出

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.