One of the most common programming tasks is that of reading lines or records from input sources. Conscientious programmers who care about good human interface design prefer not to arbitrarily limit the lengths of lines that may be read in. It is therefore useful to have a function which can read a record while automatically reallocating the buffer into which the data is being stored.
Libretto provides the following functions, which use the ‘mem_alloc’ and ‘mem_realloc’ functions (see Memory allocation) to perform memory allocation. They are therefore subject to normal memory allocation semantics.
This function reads a line from the open file represented by stream into the buffer pointed to by *lineptr. *lineptr should be either a block returned by ‘malloc’ or a variant (including mem_alloc), or a null pointer. n should contain the size of the allocated block in *lineptr, or 0 if *lineptr is a null pointer. ‘file_getline’ reads from stream until encountering a newline, and stores the line (including a terminating null character, but not including the newline) into *lineptr, reallocating as necessary. Null characters in the input are silently dropped. On exit, lineptr points to the (possibly reallocated) buffer, and n points to the size of the allocated block. ‘file_getline’ returns the length of the line read, or ‘EOF’ if an error or an end-of-file condition was encountered.
This function acts exactly like ‘file_getline’, except that an arbitrary record is read, rather than a line. delim is the character which delimits a record; as with ‘file_getline’, no instance of this character is placed in *lineptr. Although null characters are silently dropped, it is permissible to request that a null character should be used as the delimiter.