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 (1)

Collapse
 
ddebajyati profile image
Debajyati Dey

This is the content I want. You are a legend