getchar() and stdin

后端 未结 3 1835
野性不改
野性不改 2021-02-09 04:27

A related question is here, but my question is different.

But, I\'d like to know more about the internals of getchar() and stdin. I know that getchar() just ultimately c

3条回答
  •  梦谈多话
    2021-02-09 04:53

    I know that getchar() just ultimately calls fgetc(stdin).

    Not necessarily. getchar and getc might as well expand to the actual procedure of reading from a file, with fgetc implemented as

    int fgetc(FILE *fp)
    {
        return getc(fp);
    }
    

    Hey, there's nothing in the buffer, so let stdin gather what the user types. [...] it seems this is more of a behavioral artifact of stdin rather than fgetc().

    I can only tell you what I know, and that is how Unix/Linux works. On that platform, a FILE (including the thing that stdin points to) holds a file descriptor (an int) that is passed to the OS to indicate from which input source the FILE gets data, plus a buffer and some other bookkeeping stuff.

    The "gather" part then means "call the read system call on the file descriptor to fill the buffer again". This varies per implementation of C, though.

提交回复
热议问题