fgets() 是否总是以 \0 终止字符缓冲区?
即使已经达到 EOF,fgets() 是否总是以 \0 终止字符缓冲区?看起来确实如此(在 ANSI K&R 书中介绍的实现中确实如此),但我想我会要求确认一下。
我想这个问题也适用于其他类似的函数,例如 gets()。
编辑:我知道 \0 是在“正常”情况下附加的,我的问题是针对 EOF 或错误条件。例如:
FILE *fp;
char b[128];
/* ... */
if (feof(fp)) {
/* is \0 appended after EACH of these calls? */
fgets(b, 128, fp);
fgets(b, 128, fp);
fgets(b, 128, fp);
}
Does fgets() always terminate the char buffer with \0 even if EOF is already reached? It looks like it does (it certainly does in the implementation presented in the ANSI K&R book), but I thought I would ask to be sure.
I guess this question applies to other similar functions such as gets().
EDIT: I know that \0 is appended during "normal" circumstances, my question is targeted at EOF or error conditions. For example:
FILE *fp;
char b[128];
/* ... */
if (feof(fp)) {
/* is \0 appended after EACH of these calls? */
fgets(b, 128, fp);
fgets(b, 128, fp);
fgets(b, 128, fp);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
fgets
总是向读取缓冲区添加一个“\0”,它最多从流中读取size - 1
个字符(size
是第二个参数)因此。永远不要使用
gets
因为你永远不能保证它不会溢出你给它的任何缓冲区,所以虽然它在技术上总是终止读取字符串,但这实际上没有帮助。fgets
does always add a '\0' to the read buffer, it reads at mostsize - 1
characters from the stream (size
being the second parameter) because of this.Never use
gets
as you can never guarantee that it won't overflow any buffer that you give it, so while it technically does always terminate the read string this doesn't actually help.永远不要使用 gets!!
因此,是的,当
fgets()
不返回 NULL 时,目标数组始终有一个空字符。如果
fgets()
返回 NULL,则目标数组可能已更改并且可能没有空字符。从fgets()
获取 NULL 后,切勿依赖数组。添加编辑示例
看到了吗? buf 中没有 NUL :)
Never use gets!!
So, yes, when
fgets()
does not return NULL the destination array always has a null character.If
fgets()
returns NULL, the destination array may have been changed and may not have a null character. Never rely on the array after getting NULL fromfgets()
.Edit example added
See? no NUL in buf :)
man fgets:
fgets() 从流中最多读入一个小于 size 的字符,并将它们存储到 s 指向的缓冲区中。读取在 EOF 或换行符后停止。如果读取新行,则将其存储到缓冲区中。 “\0”存储在缓冲区中最后一个字符之后。
man fgets:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a new‐line is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.
如果您确实以二进制模式“rb”打开文件,并且如果您想使用 fgets 逐行读取文本,则可以使用以下代码来保护您的软件不会丢失文本,如果文本错误地包含 '\ 0' 字节。
但最后就像提到的其他人一样,如果流包含 '\0',通常您不应该使用
fgets
。If you did open the file in binary mode "rb", and if you want to read Text line by line by using fgets you can use the following code to protect your software of loosing text, if by a mistake the text contained a '\0' byte.
But finally like the others mentioned, normally you should not use
fgets
if the stream contains '\0'.是的,确实如此。来自 CPlusPlus.com
Yes it does. From CPlusPlus.com