DEV Community

Cover image for Building Linux Commands From Scratch 🐧 clear Command
Suraj Kareppagol
Suraj Kareppagol

Posted on

Building Linux Commands From Scratch 🐧 clear Command

Here i am building clear command from scratch in C/C++. The clear command is used to clear the terminal screen.


This command can be implemented in many ways. Here are some of the methods.

#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>

int main()
{
  // Get Terminal Size

  struct winsize w;
  ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);

  // printf("%d %d\n", w.ws_row, w.ws_col);

  for (int i = 0; i < w.ws_row + 40; i++)
    printf("\n");

  printf("\033[0;0H");

  return 0;
}
Enter fullscreen mode Exit fullscreen mode
struct winsize w;
Enter fullscreen mode Exit fullscreen mode

Here winsize is a structure that has ws_row, ws_col as members. This can be populated using ioctl().

ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
Enter fullscreen mode Exit fullscreen mode
int ioctl(int __fd, unsigned long __request, );
Enter fullscreen mode Exit fullscreen mode

This is the function prototype of the ioctl().

Clear Command

Here we will print “\n” for Terminal Rows + 40 times. This will although works but the prompt will be moved to the bottom. However ASCII sequence “[m;hH” can be used to move the cursor to the top left of the terminal.

Clear Command

printf("\033[0;0H");
Enter fullscreen mode Exit fullscreen mode

This will move the cursor back to the top left of the terminal.

This is will work exactly like clear command, but there is another ASCII sequence that will directly clear the terminal screen.

Clear Command

printf("\033c");
Enter fullscreen mode Exit fullscreen mode

This is another method for writing the clear command and an easy one (just one line to clear the screen).

#include <stdio.h>

int main()
{
  printf("\033c");

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Clear Command

Also instead of loop and ASCII sequence, the ASCII sequence also works just fine.

#include <stdio.h>

int main()
{
  printf("\033[0;0H");

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Clear Command

The code can be found at GitHub.

Top comments (0)