Windows console clear screen

Очистка экрана Clearing the Screen

Существует четыре способа очистки экрана в консольном приложении. There are four ways to clear the screen in a console application.

Пример 1 Example 1

Это рекомендуемый метод с использованием виртуальных последовательностей терминалов для всех новых разработок. This is the recommended method using virtual terminal sequences for all new development. Дополнительные сведения см. в обсуждении классических API консоли и виртуальных последовательностей терминалов . For more information, see the discussion of classic console APIs versus virtual terminal sequences .

Первый способ — настроить приложение для виртуальных выходных последовательностей терминала, а затем вызвать команду «очистить экран». The first method is to set your application up for virtual terminal output sequences and then call the «clear screen» command.

Дополнительные варианты этой команды см. в документации по виртуальным последовательностям, посвященной стиранию экрана . You can find additional variations on this command in the virtual terminal sequences documentation on Erase In Display .

Пример 2 Example 2

Второй метод — написать функцию для прокрутки содержимого экрана или буфера и задать заливку для видимого пространства. The second method is to write a function to scroll the contents of the screen or buffer and set a fill for the revealed space.

Это соответствует поведению командной строки cmd.exe . This matches the behavior of the command prompt cmd.exe .

Пример 3 Example 3

Третий метод заключается в написании функции для программного очистки экрана с помощью функций филлконсолеаутпутчарактер и филлконсолеаутпутаттрибуте . The third method is to write a function to programmatically clear the screen using the FillConsoleOutputCharacter and FillConsoleOutputAttribute functions.

Этот прием показан в следующем образце кода. The following sample code demonstrates this technique.

Console. Clear Метод

Определение

Удаляет из буфера консоли и ее окна отображаемую информацию. Clears the console buffer and corresponding console window of display information.

Исключения

Ошибка ввода/вывода. An I/O error occurred.

Примеры

В следующем примере Clear метод очищает консоль перед выполнением цикла, предложит пользователю выбрать цвет переднего плана и фона и ввести строку для вывода. The following example uses the Clear method to clear the console before it executes a loop, prompts the user to select a foreground and background color and to enter a string to display. Если пользователь решил не выходить из программы, восстанавливаются исходные цвета и цвет фона консоли, а Clear метод вызывается снова перед повторным выполнением цикла. If the user chooses not to exit the program, the console’s original foreground and background colors are restored and the Clear method is called again before re-executing the loop.

В этом примере используется GetKeyPress метод для проверки выбора пользователем переднего плана и цвета фона. The example relies on a GetKeyPress method to validate the user’s selection of a foreground and background color.

В этом примере демонстрируются CursorLeft CursorTop Свойства и, а SetCursorPosition также Clear методы и. This example demonstrates the CursorLeft and CursorTop properties, and the SetCursorPosition and Clear methods. В примере размещается курсор, который определяет, где будет выполняться следующая запись, чтобы нарисовать 5-символьный прямоугольник на 5 символов, используя сочетание строк «+», «|» и «-«. The example positions the cursor, which determines where the next write will occur, to draw a 5 character by 5 character rectangle using a combination of «+», «|», and «-» strings. Обратите внимание, что прямоугольник может быть нарисован с меньшим количеством шагов, используя сочетание других строк. Note that the rectangle could be drawn with fewer steps using a combination of other strings.

Читайте также:  Windows remove file cmd windows

Комментарии

Использование Clear метода эквивалентно вызову cls команды MS-DOS в окне командной строки. Using the Clear method is equivalent invoking the MS-DOS cls command in the command prompt window. При Clear вызове метода курсор автоматически прокручивается к левому верхнему углу окна, а содержимое буфера экрана устанавливается в пустое значение с использованием текущих фоновых цветов переднего плана. When the Clear method is called, the cursor automatically scrolls to the top-left corner of the window and the contents of the screen buffer are set to blanks using the current foreground background colors.

Попытка вызвать метод, Clear когда выходные данные консольного приложения перенаправляется в файл, вызывает исключение IOException . Attempting to call the Clear method when a console application’s output is redirected to a file throws a IOException. Чтобы избежать этого, всегда заключайте вызов Clear метода в try . catch To prevent this, always wrap a call to the Clear method in a try … catch блок. block.

Console. Clear Method

Definition

Clears the console buffer and corresponding console window of display information.

Exceptions

An I/O error occurred.

Examples

The following example uses the Clear method to clear the console before it executes a loop, prompts the user to select a foreground and background color and to enter a string to display. If the user chooses not to exit the program, the console’s original foreground and background colors are restored and the Clear method is called again before re-executing the loop.

The example relies on a GetKeyPress method to validate the user’s selection of a foreground and background color.

This example demonstrates the CursorLeft and CursorTop properties, and the SetCursorPosition and Clear methods. The example positions the cursor, which determines where the next write will occur, to draw a 5 character by 5 character rectangle using a combination of «+», «|», and «-» strings. Note that the rectangle could be drawn with fewer steps using a combination of other strings.

Remarks

Using the Clear method is equivalent invoking the MS-DOS cls command in the command prompt window. When the Clear method is called, the cursor automatically scrolls to the top-left corner of the window and the contents of the screen buffer are set to blanks using the current foreground background colors.

Attempting to call the Clear method when a console application’s output is redirected to a file throws a IOException. To prevent this, always wrap a call to the Clear method in a try … catch block.

How do you clear the console screen in C?

Is there a «proper» way to clear the console window in C, besides using system(«cls») ?

13 Answers 13

Well, C doesn’t understand the concept of screen. So any code would fail to be portable. Maybe take a look at conio.h or curses, according to your needs?

Portability is an issue, no matter what library is used.

This function will work on ANSI terminals, demands POSIX. I assume there is a version that might also work on window’s console, since it also supports ANSI escape sequences.

There are some other alternatives, some of which don’t move the cursor to <1,1>.

For portability, try this:

Then simply call clrscr() . On Windows, it will use conio.h ‘s clrscr() , and on Linux, it will use ANSI escape codes.

If you really want to do it «properly», you can eliminate the middlemen ( conio , printf , etc.) and do it with just the low-level system tools (prepare for a massive code-dump):

A workaround tested on Windows(cmd.exe), Linux(Bash and zsh) and OS X(zsh):

Using macros you can check if you’re on Windows, Linux, Mac or Unix, and call the respective function depending on the current platform. Something as follows:

Since you mention cls , it sounds like you are referring to windows. If so, then this KB item has the code that will do it. I just tried it, and it worked when I called it with the following code:

Читайте также:  Create windows 10 usb install media

There is no C portable way to do this. Although various cursor manipulation libraries like curses are relatively portable. conio.h is portable between OS/2 DOS and Windows, but not to *nix variants.

The entire notion of a «console» is a concept outside of the scope of standard C.

If you are looking for a pure Win32 API solution, There is no single call in the Windows console API to do this. One way is to FillConsoleOutputCharacter of a sufficiently large number of characters. Or WriteConsoleOutput You can use GetConsoleScreenBufferInfo to find out how many characters will be enough.

You can also create an entirely new Console Screen Buffer and make the current one.

Clear the screen

Contents

Introduction

This short article describes the method of clearing the console display of all text and positioning the text cursor in the home location (the upper-left corner).

Before becoming too comfortable doing this kind of thing blithely, make sure you read and understand about the types and purposes of console applications (and why it matters).

Throughout this article the code snippits will not assume either C or C++, so the #include section will be bracketed by the appropriate #ifdef tests depending on which language you are using. If you know yourself to be using just one, you can get rid of everything except for the proper #includes.

If you don’t know what that entails, don’t worry about it.

OS Agnostic Ways

The following methods are usually supported by a wide variety of platforms, but have significant tradeoffs in functionality or utility or both.

The Simple Answer

While simple, it really is a Bad Thing. See Why system() is evil for more information.

The Standard Way

This method is pathetic, but does the job, and it is usually correct.

This works, of course, just by putting a hundred newlines to the display. Over a poorly-buffered network connection, this might be s l o w. Alas.

Using Curses

Again, if all you want to do is clear the screen on occasion, then it is complete overkill to use Curses. (If you do use Curses, see NCurses for Unix and Linux and other POSIX systems, and PDCurses for DOS, Windows, OS/2, and some other random systems.)

Using

This library is severely deprecated, but it is so popular (due to hysterical raisins) that some form of it exists on most 80×86 hardware compilers —almost always on Windows compilers, and there exist Linux versions too. However, given the choice, use Curses instead.

The caveat is that it is non-standard, meaning that the actual functions it provides vary a lot and they don’t always behave just right. Hence, for anything other than Windows programs it is also a sub-optimal solution. (See Wikipedia’s Conio article for a very succinct description of its limitations.)

If undaunted, then here is some code:

Now, the enterprising among you may have already tried to compile this. If it worked for you, then you are lucky. If not, then you have learned firsthand the shortcomings of the library. Alas.

OS Specific Ways

So, on to the part for those of us who have the hack nature: we want to do it the Right Way.

Windows API

The Windows Console has a specific-size buffer of cell data, organized exactly the same as the old EGA/VGA/HGC cards but with user-specified dimensions: each «cell» contains attribute information (colors) and a character code (for simplicity, you can consider this the ASCII code — its actual meaning depends on the current Code Page). Clearing the screen is, therefore, a simple method of writing the current character attribute and a space character to every cell on the screen, then positioning the cursor at (0,0).

Читайте также:  Оснастка active directory windows 10 2004

POSIX (Unix, Linux, Mac OSX, etc)

Unix systems are not so simple. While PC hardware follows a very strict standard, Unix systems work with more than a few different kinds of hardware. (Hundreds, actually.) In an effort to make writing programs for all these different types of terminals easier, a fellow by the name of Bill Joy wrote the termcap library, which has been (long since) superceded by the terminfo library, first programmed by Mark Horton and significantly updated and maintained by Eric S. Raymond.

The terminfo database and library makes querying and using advanced terminal features relatively easy. The caveat is, of course, you may be stuck on some ancient dinosaur that does not support the feature you desire, like «clear and home». (Fortunately, the vast majority of modern terminals do.)

Fortunately, since the terminal can do this stuff, the resulting code is quite a bit shorter than the Windows version:

You’ll have to link to the proper library (one of -lcurses , -lterminfo , etc) to compile that last one. If neither of those work, you will have to ask your system administrator what to link to. I know that on some old SunSPARC workstations you have to link with -lncurses to get the proper library.

Other systems, like DOS

This article specifically addresses modern systems. If you are using an older system, such as DOS or something really weird, you will have to look up your system’s documentation. For example, on DOS, you would have to use the Video Interrupt functions to do it, or, as optimized programs often did, simply write directly to video memory. The ins and outs of this kind of thing are ancient, esoteric stuff. Good luck!

Addenda

This article, as it originally appeared, attracted some commentary, both good and bad. What follows is edited from that commentary to answer some valid questions.

ANSI Escape Codes

Why not just emit an ANSI Escape code, like printf( «\033[2J» ); ?

The answer is that it might not work. As explained above in the introduction to the POSIX code, not all terminals take the ANSI/VT100+ escape sequences. (DOS and Windows, remember, has the suboptimal solution of requiring your user to have loaded ANSI.SYS — just to use a small subset of those escape sequences!) But beyond that, it is actually possible that the terminal gets something other than what you think, because stuff that you printf() might be modified some before it gets to the terminal itself!

The best way to do it on *nix systems is to use the putp() function to properly communicate with the terminal, and to use the tigetstr() function(s) to get the proper terminal escape sequence to send. It may very well be «\033[2J». It might not. If you use the terminfo database, your program will work almost everywhere, instead of mysteriously printing garbage or failing on a good number of systems.

On Windows, do things the Windows way.

Wait, how do I use this stuff?

This doesn’t technically belong here, but the question came up about actually using this code. All the above examples are snippets, which you should know how to properly integrate into your program. For simple stuff, it is enough to just copy and paste the code into your program somewhere before it is used.

However, if you really want to get fancy and use multiple files, here is the quick-n-dirty:

Do not define functions in header files. You should only prototype them.

To use the code, you need to do two things.

Оцените статью