Clear the Screen

Difficulty: ★ ☆ ☆ ☆

If you’ve studied the terminal window at any length, you probably know about the clear command, which clears the screen. Under MS-DOS, and on my old TRS-80, the command is cls. Same thing.

Clearing the screen is a visual effect for a modern terminal window. Those terminals with a scroll-back buffer retain all the previous text output. But the visible screen is wiped clear of all text, the cursor flown to the upper left corner, with only the command prompt visible.

In my programming travels, I’ve witnessed a few dorky ways to clear the screen. Perhaps the most stupid was a program that just output a series of blank newlines. While this effect removed text from the screen, it didn’t “home” the cursor. No, the cursor remained squat in the lower left corner where I didn’t wanted it.

C uses streaming I/O, so it doesn’t care about clearing the screen. When you think about streaming I/O historically, how would you clear the “screen” on a teletype? The answer is that you can’t, though a command was available to eject a page: Ctrl+L. ASCII code 12 still ejects a page on modern printers. On some terminals, outputting a Ctrl+L character clears the terminal screen — but not all.

To clear the screen on a Linux terminal, you can output one or more ANSI escape codes. I’ve covered ANSI codes a few times in this blog, for example to output inverse text. You can use similar codes to clear the screen.

Rather than have you hunt for ANSI codes to output, I’ve included a few screen and cursor manipulation codes for your reference in the following table.

Code Description
\f Form feed / New Page
\e[H Move cursor to home position (0,0)
\e[0J Erase from cursor to the end of the screen
\e[1J Erase from cursor to the beginning of the screen
\e[2J Erase the entire screen
\e[3J Erase saved lines
\e[0K Erase from the cursor to the end of the line
\e[2K Erase the entire line

Your task for this month’s exercise, is to output one or more ANSI codes to clear the screen. Put your solution into a function called cls(), in honor of MS-DOS. Here is a code skeleton to get you started:

2024_07_01-Lesson.c

#include <stdio.h>

void cls(void)
{
    /* output ANSI code(s) here */
}

int main()
{
    printf("Prepare to clear the screen!");
    getchar();
    cls();

    return 0;
}

Please try this exercise on your own before you see my solution, which I’ll post in a week.

Leave a Reply