[CODE] [LIB] alternate file_to_string

From: d. hall (dhall@OOI.NET)
Date: 08/10/98


Recently saw some discussion (I don't remember if it was this list) about
function text buffer limitations.  The function file_to_string() in db.c
does possess such a limitation.  When reading in a file greater than
MAX_STRING_LENGTH in size, you'll exceed the temp buffer.  This may be a
problem with certain files, especially policies, handbook and background.
The obvious solution is to write shorter files, but if you'll want to hack
the source some, here is a replacement.

Please note, the method of calling it is completely different, in order to
simplify it's use.

char *file_to_string (char *path) {
        FILE *fh;

        if ((fh = fopen (path, "r")) == NULL) {
                perror ("fopen");
                return NULL;
        } else {
                char *buffer, *b_point;
                long measure;
                int b_taken, b_empty, b_read, nl_left;

                /* measure and rewind */
                fseek (fh, 0, SEEK_END);
                measure = ftell (fh);
                rewind (fh);
                nl_left = 50;
                measure += nl_left;

                /* assume 50 newlines, heuristic value */
                b_empty = measure;
                b_taken = 0;

                /* allocate initial guess, may have to realloc */
                CREATE (buffer, char, b_empty);
                b_point = buffer;

                /* fgets returns NULL on EOF, or maybe error */
                while (fgets (b_point, b_empty, fh) != NULL) {
                        /* since we're adding linefeeds, increment */
                        b_read = strlen (point) + 1;
                        b_taken += b_read;
                        b_empty -= b_read;
                        b_point += b_read;
                        nl_left --;
                        /* no newline padding left?  then realloc */
                        if (nl_left < 1) {
                                nl_left += 50;
                                b_empty += nl_left;
                                measure += nl_left;
                                RECREATE (buffer, char, measure);
                                b_point = buffer + b_taken;
                        }
                        strcpy (b_point - 2, "\r\n");
                }
                fclose (fh); /* should probably put a EOF check here */
                return buffer;
        }
}


     +------------------------------------------------------------+
     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     | http://democracy.queensu.ca/~fletcher/Circle/list-faq.html |
     +------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/15/00 PST