Question

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;
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top