gets() function and '\\0' zero byte in input

可紊 提交于 2019-12-01 12:41:24

The behavior of gets() is that it stops when a newline character is encountered or if EOF is encountered. It does not care if it reads \0 bytes.

C99 Standard, 7.19.7.7

Synopsis

   #include <stdio.h>

   char *gets(char *s);

Description

The gets function reads characters from the input stream pointed to by stdin, into the array pointed to by s, until end-of-file is encountered or a new-line character is read. Any new-line character is discarded, and a null character is written immediately after the last character read into the array.

From GNU libc documentation: http://www.gnu.org/software/libc/manual/html_node/Line-Input.html#Line-Input

— Deprecated function: char * gets (char *s)

The function gets reads characters from the stream stdin up to the next newline character, and stores them in the string s. The newline character is discarded (note that this differs from the behavior of fgets, which copies the newline character into the string). If gets encounters a read error or end-of-file, it returns a null pointer; otherwise it returns s.

It will not stop at zero byte.

$ cat gets22.c
int main(int argc, char **argv) {
  char array[8];
  gets(array);
  printf("%c%c%c%c%c%c%c\n",array[0],array[1],array[2],array[3],array[4],array[5],array[6],array[7]);
  printf("%d %d %d %d %d %d %d\n",array[0],array[1],array[2],array[3],array[4],array[5],array[6],array[7]);
}

$ gcc gets22.c  -o gets22

$ echo -ne 'AB\0CDE'| ./gets22
ABCDE
65 66 0 67 68 69 0
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!