gets()
函数来自C语言(例如来自glibc),如果它从文件中读取到一个零字节('\0'
),会停止吗?
快速测试:echo -ne 'AB\0CDE'
谢谢。
PS:这个问题源自于此问题的评论:return to libc - problem
PPS:虽然 gets
函数很危险,但这个问题是关于该函数本身的,而不是关于是否应该使用它。
gets()
函数来自C语言(例如来自glibc),如果它从文件中读取到一个零字节('\0'
),会停止吗?
快速测试:echo -ne 'AB\0CDE'
谢谢。
PS:这个问题源自于此问题的评论:return to libc - problem
PPS:虽然 gets
函数很危险,但这个问题是关于该函数本身的,而不是关于是否应该使用它。
gets()
函数的行为是,当遇到换行符或 EOF 时停止读取。它不会在意是否读取了 \0
字节。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 bys
, 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遇到读取错误或文件结束,则返回空指针;否则返回字符串
。
$ 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
gets
函数:https://dev59.com/nXI-5IYBdhLWcg3wwLS3 - Jeremiah Willcockgets
来说明其危险性(请参见链接的Q)。 - osgx