Skip to content
On this page

getchar()


标签:linux/basic  

[!note] tl;dr

c
getchar() == fgetc(stdin) ~= getc(stdin)

getc()

c
int getchar();

从标准输入流中获取一个字符,所以它等价于:

c
getc(stdin);

getc 等同于 fgetc ,除了它是宏实现的(f代表function)。

[!quote] man fgetc

fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error.

getc() is equivalent to fgetc() except that it may be implemented as a macro which evaluates stream more than once.

getchar() is equivalent to getc(stdin).

与输入相对应的是输出函数 putchar()

特点

  1. 最多读取 size - 1 个字符
  2. 读到\n 读取结束
  3. 每次遇到\n 读取结束后,自动添加\0
利用 fgets 读取下列数据, 一共需要几次, 
每次存到 buf 的是什么
=========================================
'a', 'b', '\n',
'c', '\0', 'd', 'e', 'f', 'g', 'j', '\n',
'\0', 'x', 'y', '\n'
=========================================
char buf[5];

FILE *fp = fopen("log.txt", "r");
fgets(buf, 5, fp);

结果是:

第一次:    a    b '\n' '\0'
第二次:    c '\0'    d   e   '\0'
第三次:    f    g    j '\n'  '\0'
第四次: '\0'    x    y '\n'  '\0'

为什么返回 int

[!quote]

fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error.

fget 手册有上面一段描述,它会把 unsigned char 作为 int 类型读入。这是因为中文字符在计算机中的保存的大小是 4 个字节,所以 unsigned char 对于非英文的字符是不够用的。

fgets()

c
char *fgets(char *s, int size, FILE *stream);
  • fgets() 的读取会被 \0 中断

其他标准输入函数:

Last updated: