dev*_*urs 51 c windows console console-application
是否有一种"正确"的方式来清除C中的控制台窗口,除了使用system("cls")?
小智 27
printf("\e[1;1H\e[2J");
Run Code Online (Sandbox Code Playgroud)
此功能适用于ANSI终端,需要POSIX.我假设有一个版本可能也适用于窗口的控制台,因为它也支持ANSI转义序列.
#include <unistd.h>
void clearScreen()
{
const char *CLEAR_SCREEN_ANSI = "\e[1;1H\e[2J";
write(STDOUT_FILENO, CLEAR_SCREEN_ANSI, 12);
}
Run Code Online (Sandbox Code Playgroud)
还有一些其他 选择,其中一些不会将光标移动到{1,1}.
Jam*_*its 11
在Windows(cmd.exe),Linux(Bash和zsh)和OS X(zsh)上测试的变通方法:
#include <stdlib.h>
void clrscr()
{
system("@cls||clear");
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ins 10
既然你提到cls,听起来你指的是windows.如果是这样,则此KB项具有将执行此操作的代码.我刚试过它,当我用以下代码调用它时它工作了:
cls( GetStdHandle( STD_OUTPUT_HANDLE ));
Run Code Online (Sandbox Code Playgroud)
使用宏可以检查您是否在Windows,Linux,Mac或Unix上,并根据当前平台调用相应的函数。如下所示:
void clear(){
#if defined(__linux__) || defined(__unix__) || defined(__APPLE__)
system("clear");
#endif
#if defined(_WIN32) || defined(_WIN64)
system("cls");
#endif
}
Run Code Online (Sandbox Code Playgroud)
#include <conio.h>
Run Code Online (Sandbox Code Playgroud)
并使用
clrscr()
Run Code Online (Sandbox Code Playgroud)
为了便于携带,请尝试以下操作:
#ifdef _WIN32
#include <conio.h>
#else
#include <stdio.h>
#define clrscr() printf("\e[1;1H\e[2J")
#endif
Run Code Online (Sandbox Code Playgroud)
然后只需致电即可clrscr()。在Windows上,它将使用conio.h的clrscr(),在Linux上,它将使用ANSI转义码。
如果您真的想“适当地”执行此操作,则可以消除中间商(conio,printf等),而仅使用低级系统工具(准备进行大规模的代码转储)即可:
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
void ClearScreen()
{
HANDLE hStdOut;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
if (hStdOut == INVALID_HANDLE_VALUE) return;
/* Get the number of cells in the current buffer */
if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
cellCount = csbi.dwSize.X *csbi.dwSize.Y;
/* Fill the entire buffer with spaces */
if (!FillConsoleOutputCharacter(
hStdOut,
(TCHAR) ' ',
cellCount,
homeCoords,
&count
)) return;
/* Fill the entire buffer with the current colors and attributes */
if (!FillConsoleOutputAttribute(
hStdOut,
csbi.wAttributes,
cellCount,
homeCoords,
&count
)) return;
/* Move the cursor home */
SetConsoleCursorPosition( hStdOut, homeCoords );
}
#else // !_WIN32
#include <unistd.h>
#include <term.h>
void ClearScreen()
{
if (!cur_term)
{
int result;
setupterm( NULL, STDOUT_FILENO, &result );
if (result <= 0) return;
}
putp( tigetstr( "clear" ) );
}
#endif
Run Code Online (Sandbox Code Playgroud)
没有C便携式方法可以做到这一点.虽然像curses这样的各种游标操作库都相对便携. conio.h可在OS/2 DOS和Windows之间移植,但不适用于*nix变体.
"控制台"的整个概念是标准C范围之外的概念.
如果您正在寻找纯Win32 API解决方案,则Windows控制台API中没有单个调用来执行此操作.一种方法是FillConsoleOutputCharacter具有足够多的字符.或WriteConsoleOutput您可以使用GetConsoleScreenBufferInfo来找出足够多的字符.
您还可以创建一个全新的控制台屏幕缓冲区并创建当前的控制台屏幕缓冲区.