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;
}
struct winsize w;
Here winsize is a structure that has ws_row, ws_col as members. This can be populated using ioctl().
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
int ioctl(int __fd, unsigned long __request, โฆ);
This is the function prototype of the ioctl().
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.
printf("\033[0;0H");
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.
printf("\033c");
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;
}
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;
}
The code can be found at GitHub.
Top comments (1)
This is the content I want. You are a legend