fgets() 是否总是以 null 结尾它返回的字符串?
这样做安全吗? fgets
是否以 null 终止缓冲区,或者我应该在调用 fgets
之后、调用 clean
之前将第 20 个字节设置为 null?
// strip new lines
void clean(char *data)
{
while (*data)
{
if (*data == '\n' || *data == '\r') *data = '\0';
data++;
}
}
// for this, assume that the file contains 1 line no longer than 19 bytes
// buffer is freed elsewhere
char *load_latest_info(char *file)
{
FILE *f;
char *buffer = (char*) malloc(20);
if (f = fopen(file, "r"))
if (fgets(buffer, 20, f))
{
clean(buffer);
return buffer;
}
free(buffer);
return NULL;
}
Is this safe to do? Does fgets
terminate the buffer with null or should I be setting the 20th byte to null after the call to fgets
and before I call clean
?
// strip new lines
void clean(char *data)
{
while (*data)
{
if (*data == '\n' || *data == '\r') *data = '\0';
data++;
}
}
// for this, assume that the file contains 1 line no longer than 19 bytes
// buffer is freed elsewhere
char *load_latest_info(char *file)
{
FILE *f;
char *buffer = (char*) malloc(20);
if (f = fopen(file, "r"))
if (fgets(buffer, 20, f))
{
clean(buffer);
return buffer;
}
free(buffer);
return NULL;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,
fgets()
总是正确地以 null 终止缓冲区。从 手册页:Yes
fgets()
always properly null-terminates the buffer. From the man page:如果出现错误,fgets() 可能会也可能不会在缓冲区中的任何位置存储任何零字节。不检查 fgets() 返回值的代码将不安全,除非它确保缓冲区中某处有零;最简单的方法是无条件地将零存储到最后一个位置。这样做意味着未被注意到的错误可能(取决于实现)导致读取虚假的额外数据行,但不会陷入未定义的行为。
If there is an error, fgets() may or may not store any zero bytes anywhere in the buffer. Code which doesn't check the return value of fgets() won't be safe unless it ensures there's a zero in the buffer somewhere; the easiest way to do that is to unconditionally store a zero to the last spot. Doing that will mean that an unnoticed error may (depending upon implementation) cause a bogus extra line of data to be read, but won't fall off into Undefined Behavior.