มีหลายวิธีในการเคลียร์หน้าจอ Console ใน C ขึ้นอยู่กับ Platform และ Compiler
วิธีที่ 1: clrscr() (Turbo C / Borland / DOS)
#include <conio.h>
void main() {
clrscr(); // เคลียร์หน้าจอ
printf("Hello World");
getch();
}
ข้อจำกัด: เฉพาะ Turbo C, Borland C, DOS/Windows Console แบบเก่า ไม่ทำงานใน GCC/Clang/Linux/macOS
วิธีที่ 2: system("cls") / system("clear") (Cross-platform-ish)
#include <stdlib.h>
int main() {
#ifdef _WIN32
system("cls"); // Windows
#else
system("clear"); // Linux, macOS, Unix
#endif
printf("Screen Cleared!");
return 0;
}
ข้อเสีย: ช้า (Spawn Process), ไม่ปลอดภัย (Security Risk), ไม่ Portable แท้ๆ
วิธีที่ 3: ANSI Escape Codes (Modern Terminals - Linux/macOS/Windows 10+)
#include <stdio.h>
void clearScreen() {
printf("\033[2J\033[H"); // Clear Screen + Move Cursor to Home
// หรือ
// printf("\033[H\033[2J");
}
int main() {
printf("Before Clear\n");
clearScreen();
printf("After Clear");
return 0;
}
Escape Codes:
\033[2J- Clear Entire Screen (ESC [ 2 J)\033[H- Move Cursor to Home (0,0) (ESC [ H)\033[1J- Clear from Cursor to Start\033[0J- Clear from Cursor to End
วิธีที่ 4: Windows API (Windows เท่านั้น - เร็วและปลอดภัยกว่า system)
#include <windows.h>
void clearScreen() {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord = {0, 0};
DWORD count;
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hConsole, &csbi);
FillConsoleOutputCharacter(hConsole, ' ', csbi.dwSize.X * csbi.dwSize.Y, coord, &count);
SetConsoleCursorPosition(hConsole, coord);
}
วิธีที่ 5: Cross-platform Function (แนะนำ)
#include <stdio.h>
#include <stdlib.h>
void clearScreen() {
#ifdef _WIN32
// Windows 10+ รองรับ ANSI Escape Codes
// ต้อง Enable Virtual Terminal Processing ก่อน
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD dwMode = 0;
GetConsoleMode(hOut, &dwMode);
SetConsoleMode(hOut, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
printf("\033[2J\033[H");
#else
// Linux, macOS, Unix
printf("\033[2J\033[H");
#endif
}
int main() {
printf("Line 1\nLine 2\nLine 3\n");
clearScreen();
printf("Screen Cleared!\n");
return 0;
}
ตัวอย่างจากบทความเดิม (ใช้ clrscr)
#include <stdio.h>
#include <conio.h>
void main() {
FILE *f;
char s;
clrscr(); // เคลียร์ก่อนอ่านไฟล์
f = fopen("new.txt", "r");
while ((s = fgetc(f)) != EOF) {
printf("%c", s);
}
fclose(f);
getch();
}
สรุปแนะนำ
| สภาพแวดล้อม | วิธีแนะนำ |
|---|---|
| Linux/macOS/Unix | ANSI Escape: printf("\033[2J\033[H") |
| Windows 10+ (Modern) | ANSI Escape (Enable VT Processing) |
| Windows Legacy (XP/7) | Windows API หรือ system("cls") |
| Turbo C / DOS | clrscr() (conio.h) |
| Cross-platform Library | ncurses (C), ncursesw, PDCurses |
ข้อควรระวัง
system()มี Security Risk (Command Injection)conio.hไม่ใช่ Standard Header - ใช้ได้เฉพาะบาง Compiler- ANSI Escape Codes ต้องการ Terminal ที่รองรับ (ส่วนใหญ่รองรับแล้ว)
- ใน GUI Applications ไม่มี Console ให้ Clear