简体   繁体   English

fgets()是否始终以null终止它返回的字符串?

[英]Does fgets() always null-terminate the string it returns?

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 ? 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;
}

Yes fgets() always properly null-terminates the buffer. 是的, fgets()总是正确地以空值终止缓冲区。 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 . fgets()函数从给定流中读取的字符数最多少于n指定的字符数,并将它们存储在字符串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. 如果读取了任何字符并且没​​有错误,则在字符串末尾附加一个' \\0 '字符。

If there is an error, fgets() may or may not store any zero bytes anywhere in the buffer. 如果出现错误,fgets()可能会或可能不会在缓冲区中的任何位置存储任何零字节。 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; 不检查fgets()返回值的代码将是不安全的,除非它确保某处的缓冲区中的零。 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. 这样做将意味着未注意到的错误(取决于实现)可能导致读取额外的虚假数据行,但不会陷入未定义行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM