Sunday, February 19, 2012

implement readLine using read

http://www.mitbbs.com/article_t/JobHunting/32042617.html
char *readLine() {
    int bufSize = 1024;
    static char *buf = malloc(sizeof(char) * (1 + bufSize));
    static int bytesAfterNewLine = 0;   // number of bytes left from last call
    static int lastpos = 0;             // where the leftover starts

    int totalBytes = 0; // total number of bytes in the array
    int foundLineBreak = 0;

    if (bytesAfterNewLine != 0) {
        memmove(buf, buf + lastpos, bytesAfterNewLine);
        totalBytes = bytesAfterNewLine;
        lastpos = 0;
    }

    while (true) {
        for (; lastpos < totalBytes; ++lastpos) {
            if (buf[lastpos] == '\n') {
                buf[lastpos] == '\0';
                bytesAfterNewLine = totalBytes - lastpos - 1;
                foundLineBreak = 1;
                lastpos = (last + 1) % bufSize;
                break;
            }
        }
        if (foundLineBreak) break;

        if (bufSize == totalBytes) {
            bufSize *= 2;
            buf = realloc(buf, bufSize + 1);
        }

        int bytes = 0;
        while (true) {
            bytes = read(buf + totalBytes, bufSize - totalBytes);
            if (bytes != 0) break;
        }

        if (bytes == -1) {
            buf[totalBytes] = '\0';
            break;
        }

        totalBytes += bytes;
    }

    if (totalBytes == 0 && foundLineBreak == 0) {
        return NULL:
    } else {
        return buf;
    }
}

No comments: