3.71 fgets

Write a function good_echo that reads a line from standard input and writes it to standard output. Your implementation should work for an input line of arbitrary length. You may use the library function fgets, but you must make sure your function works correctly even when the input like requires more space than you have allocated for your buffer. Your code should also check for error conditions and return when one is encountered. Refer to the definitions of the standard I/O functions for documentation.

#include <stdio.h>
#define BUF_SIZE 12

void good_echo() {
    char buf[BUF_SIZE];
    while(1) {
        char* p = fgets(buf, BUF_SIZE, stdin);
        if(p == NULL) {
            break;
        }
        printf("%s", p);
    }
    return;
}

int main() {
    good_echo();
    return 0;
}

Last updated