C - stdio fcopyline

#include 
#include 

/// $ man getline
///
/// The getdelim() and getline() functions return the number of characters
/// written, excluding the terminating NUL character.  The value -1 is
/// returned if an error occurs, or if end-of-file is reached.
ssize_t
fcopyline(char *linep[], size_t *linecapp, FILE *stream) {
    
    /// $ man fgetc
    ///
    /// The fgetc() function obtains the next input character (if present) from
    /// the stream pointed at by stream, or the next character pushed back on the
    /// stream via ungetc(3).
    ///
    /// If successful, these routines return the next requested object from the
    /// stream.  Character values are returned as an unsigned char converted to
    /// an int.  If the stream is at end-of-file or a read error occurs, the rou-
    /// tines return EOF.  The routines feof(3) and ferror(3) must be used to
    /// distinguish between end-of-file and error.  If an error occurs, the
    /// global variable errno is set to indicate the error.  The end-of-file con-
    /// dition is remembered, even on a terminal, and all subsequent attempts to
    /// read will return EOF until the condition is cleared with clearerr(3).
    
    /// The getdelim() and getline() functions return the number of characters
    /// written, excluding the terminating NUL character.
    ssize_t written = 0;
    
    int read = 0;
    while ( 1 ) {
        read = fgetc(stream);
        
        // end-of-file or a read error occurs
        if ( read == EOF ) {
            break;
        }
        
        if ( written + 1 >= (*linecapp) ) {
            (*linecapp) += 32;
            (*linep) = realloc(*linep, *linecapp);
        }
        
        (*linep)[written] = read;
        (*linep)[written + 1] = '\0';
        written += 1;
        
        if ( read == '\n' ) {
            break;
        }
    }
    
    /// $ man getline
    /// return the number of characters written, excluding the terminating NUL character
    /// The value -1 is returned if an error occurs, or if end-of-file is reached.
    return read != EOF ? written : -1;
}

你可能感兴趣的:(C - stdio fcopyline)