gets()函数和输入中的'\ 0'零字节 [英] gets() function and '\0' zero byte in input
问题描述
如果C语言中的gets()
函数从文件中读取了零字节('\0'
),它会停止吗?
Will the gets()
function from C language (e.g. from glibc) stop, if it reads a zero byte ('\0'
) from the file ?
快速测试:echo -ne 'AB\0CDE'
谢谢.
此问题来自以下问题的评论:返回libc-问题
PS this question arises from comments in this question: return to libc - problem
PPS gets
功能很危险,但这是关于此功能本身的问题,而不是有关是否应该使用它的问题.
PPS the gets
function is dangerous, but it is a question about this function itself, not about should anybody use it or not.
推荐答案
gets()
的行为是,遇到换行符或遇到EOF时,它将停止.不管它是否读取\0
个字节.
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标准,7.19.7.7
C99 Standard, 7.19.7.7
简介
#include <stdio.h>
char *gets(char *s);
说明
gets
函数将stdin指向的输入流中的字符读取到
s
指向的数组,直到遇到文件结尾或读取换行符.
任何换行符都将被丢弃,并且在
最后一个字符读入数组.
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
From GNU libc documentation: http://www.gnu.org/software/libc/manual/html_node/Line-Input.html#Line-Input
-不推荐使用的功能:
char * gets (char *s)
函数gets
从流stdin读取字符,直到下一个换行符,并将它们存储在字符串s中.换行符将被丢弃(请注意,这与fgets的行为不同,后者将换行符复制到字符串中).如果get遇到读取错误或文件结尾,则返回空指针;否则,返回null.否则返回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.
这篇关于gets()函数和输入中的'\ 0'零字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!