question about fgets

Posted by user105033 on Stack Overflow See other posts from Stack Overflow or by user105033
Published on 2010-03-30T16:59:36Z Indexed on 2010/03/30 17:03 UTC
Read the original article Hit count: 344

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about c

    Related posts about file-io