writeBuffer.c 1.14 KB
#include <stdio.h>      /* for ferror() */
#include <string.h>     /* for memset and stuff */


int
writeBuffer(char ** buffer, unsigned int * readPos, FILE * wHandle)
{
    char * nlpos   = strchr(*buffer, '\n');
    int    written = 0;

    while (NULL != nlpos) {
        unsigned int moveSize, clearSize;
        char *       actAddr;

        *nlpos   = '\0';

        if (0 != strlen(*buffer)) {
            /* write remaining stuff to file */
            fputs(*buffer, wHandle);
            if (ferror(wHandle)) {
                return -1;
            }

            fputc('\n', wHandle);
            if (ferror(wHandle)) {
                return -1;
            }

            fflush(wHandle);
            if (ferror(wHandle)) {
                return -1;
            }

            written += strlen(*buffer) + 1;
        }

        actAddr    = *buffer + *readPos;
        moveSize   = actAddr - nlpos - 1;
        clearSize  = actAddr - *buffer - moveSize;
        memmove(*buffer, nlpos+1, moveSize);
        memset(*buffer + moveSize, 0, clearSize);
        *readPos = moveSize;

        nlpos = strchr(*buffer, '\n');
    }

    return written;
}