Lesson 22 of 23

fold

The fold Command

fold wraps long lines by inserting a newline after every width characters:

$ echo "hello world" | fold -w 5
hello
 worl
d

It is a pure character-level wrap — it does not care about words. Every width characters, a newline is inserted.

Your Implementation

Write void my_fold(const char *s, int width) that wraps lines at width characters.

Track a column counter. Print each character and increment the counter. When the counter reaches width, print a newline and reset it. Reset the counter also whenever the input has a real newline.

void my_fold(const char *s, int width) {
    int col = 0;
    while (*s) {
        if (*s == '\n') {
            putchar('\n');
            col = 0;
        } else {
            if (col == width) { putchar('\n'); col = 0; }
            putchar(*s);
            col++;
        }
        s++;
    }
}

Column Counter

col tracks how many characters have been printed on the current line. When it hits width, inject a newline and reset. Existing newlines in the input also reset the counter — the output preserves paragraph breaks.

Your Task

Implement my_fold that wraps text at width characters.

TCC compiler loading...
Loading...
Click "Run" to execute your code.