'How to clear the screen with \x1b[2j?
How do we implement clrscr()? Googling it I found that \x1b[2j can be used to clear the screen but how do we use it?
Solution 1:[1]
If you're confident that is the control sequence you need to use, then:
#include <stdio.h>
int main(void)
{
fputs("\x1b[2j", stdout);
return(0);
}
This deliberately omits the newline - but you might be better off with adding one after the 'j'. However, as Gilles points out in his answer, there are other ways to do it which have merits compared with this solution.
Solution 2:[2]
On Windows you may try
#include <tchar.h>
#include <stdio.h>
#include <windows.h>
void clrscr(void)
{
HANDLE std_out = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO cbi;
COORD origin = {0,0};
int buf_length;
GetConsoleScreenBufferInfo(std_out,&cbi);
buf_length = cbi.dwSize.X*cbi.dwSize.Y;
FillConsoleOutputCharacter(std_out,0x20,buf_length,origin,0);
FillConsoleOutputAttribute(std_out,0x07,buf_length,origin,0);
}
int _tmain(int argc, wchar_t *argv[], wchar_t *envp[])
{
DWORD i;
_tprintf(TEXT("Clear screen probe...\n"));
clrscr();
return 0;
}
"\x1b[H\x1b[2J" works on OSX.
Solution 3:[3]
This is a so called ANSI Escape Sequence that controls text terminal and will work with any ANSI compatible Terminal [1]:
\x1b[2Jclear screen and send cursor to home position.\x1b[Hsend cursor to cursor home position.
Just printf("\x1B[2J"); or echo "\x1B[2J" it or whatever print method suits you :-) I use that with printf() for initial terminal clear screen when producing a debug output logs from an embedded system over uart connection, but you can use it as well on a standard Unix-like terminal with echo :-)
Solution 4:[4]
#include <unistd.h>
write(STDOUT_FILENO, "\x1b[2J", 4);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | Tvaroh |
| Solution 3 | CeDeROM |
| Solution 4 | TechTycho |
