gets()函数和输入中的'\0'零字节

5

gets() 函数来自C语言(例如来自glibc),如果它从文件中读取到一个零字节('\0'),会停止吗?

快速测试:echo -ne 'AB\0CDE'

谢谢。

PS:这个问题源自于此问题的评论:return to libc - problem

PPS:虽然 gets 函数很危险,但这个问题是关于该函数本身的,而不是关于是否应该使用它。


2
请注意,您不应该使用 gets 函数:https://dev59.com/nXI-5IYBdhLWcg3wwLS3 - Jeremiah Willcock
@Jeremiah Willcock,当然,但这个问题是在一个最简单的堆栈溢出示例之后引起的,该示例使用gets来说明其危险性(请参见链接的Q)。 - osgx
2个回答

7
gets() 函数的行为是,当遇到换行符或 EOF 时停止读取。它不会在意是否读取了 \0 字节。
C99 标准,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.

来自GNU libc文档:http://www.gnu.org/software/libc/manual/html_node/Line-Input.html#Line-Input

——已弃用功能:char * gets(char *s)

gets函数从标准输入流中读取字符,直到下一个换行符,并将它们存储在字符串中,换行符会被丢弃(请注意,这与fgets的行为不同,后者将换行符复制到字符串中)。

如果gets遇到读取错误或文件结束,则返回空指针;否则返回字符串


2
它不会停在零字节。
$ 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接