>   - the code should probably store strlen(buf) rather than
>     always recomputing it, especially if you allow the chance
>     of 16K lines
>   - there's a bit of excessive malloc'ing going on... there's
>     no need to re-malloc buf, at least.
>
> For simplicity's sake, I'd probably just put a hard 1024-char
> limit on the total size of an entry, and just append consecutive
> lines using an stpcpy.
>
> Jeff Raven


revised again:

const int MAX_LINE_LENGTH = 1024;

int getFileEntry(FILE * fd, char *& entry)
{
    char * buf;
    int used = 0;
    int len = 0;
    
    buf = new char[MAX_LINE_LENGTH];
    entry = new char[MAX_LINE_LENGTH + 1];

    // get a line, and it's length from the file
    if ((fgets(buf, MAX_LINE_LENGTH, fd)) == 0)
    {
            fprintf(stderr, "No data read from file.\n");
            return -1;
    }
    len = strlen(buf);

    // while the current entry ends in a backslash
    while (buf[len - 1] == '\\')
    {
        // copy the buffer to the proper point in the entry
        strncpy(entry + used, buf, len);
        *(entry[used + len - 1]) = '\0';
        used += (len - 1);

        // read the next entry and length from the file
        if ((fgets(buf, MAX_LINE_LENGTH, fd)) == 0)
        {
                fprintf(stderr, "File error.\n");
                return -1;
        }
        len = strlen(buf);
    }

    // we have one last line to do
    strncpy(entry + used, buf, len);

    // delete the buffer and return
    delete[] buf;
    return 1;
}

Reply via email to