fgets() 是否总是以 null 结尾它返回的字符串?

发布于 2024-08-27 02:51:57 字数 666 浏览 9 评论 0原文

这样做安全吗? 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

云胡 2024-09-03 02:51:57

是的,fgets() 总是正确地以 null 终止缓冲区。从 手册页

fgets() 函数从给定流中最多读取比 n 指定的字符数少 1 的字符,并将它们存储在字符串 s< 中/em>。阅读停止时
在文件末尾或错误处找到换行符。换行符(如果有)将被保留。如果读取到任何字符并且没​​有错误,则为“\0”字符
附加到字符串末尾。


Yes fgets() always properly null-terminates the buffer. From the man page:

The fgets() function reads at most one less than the number of characters specified by n from the given stream and stores them in the string s. Reading stops when
a newline character is found, at end-of-file or error. The newline, if any, is retained. If any characters are read and there is no error, a '\0' character is
appended to end the string.

月朦胧 2024-09-03 02:51:57

如果出现错误,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文