C implementation of clear command

technical

Following is the code to clear the screen on terminal.

main() {write(1, "\33[H\33[2J", 7);}

Above program does nothing but writes an escape sequence on screen. Escape sequences are used to control the display properties like graphics,control cursor movements and key reassignment. Above one is specific to clear the screen. \33[H sends the cursor to home location and \33[2J clears the text on screen. It can also be used interchangeably i.e first clear the screen and then send the cursor to home location since printing of terminal info (like root@localhost] ) takes place after executing the complete process though if you write the separate programs for both escape sequences individually and then execute them sequentially, output may differ based on order of execution.

Wikipedia reference for escape sequences.

A complete list of escape sequences.

Little more explanation:

\33[ means an Escape sequence (of characters) follows just as \ means an escape character follows. Surprisingly not mentioned in the wiki or the other link! A common macro definition is:

#define     ANSI_ESCAPE_SEQUENCE(EscapeSeq)   "\33[" EscapeSeq

Leave a Reply

Your email address will not be published. Required fields are marked *