W 開頭函數雖數量不多,但涵蓋了文本窗口座標查詢、窗口定義、底層文件寫入等關鍵功能,是控制台程序與底層 I/O 開發的常用工具。
函數原型: int wherex(void);
功能: 返回當前文本窗口內光標的 X 座標 (1-based,最左列為 1)。
函數原型: int wherey(void);
功能: 返回當前文本窗口內光標的 Y 座標 (1-based,最上行为 1)。
示例:
#include <conio.h>
#include <stdio.h>
int main(void) {
clrscr();
gotoxy(10, 10);
cprintf("Current location is X: %d Y: %d\r\n", wherex(), wherey());
getch();
return 0;
}
函數原型: void window(int left, int top, int right, int bottom);
功能: 設置文本模式下的虛擬窗口邊界。後續的 clrscr、gotoxy、cprintf 等操作均限制在該窗口內,座標以窗口左上角為原點 (1,1)。
參數: 左、上、右、下邊界 (包含),均為屏幕絕對座標。
示例:
#include <conio.h>
int main(void) {
window(10, 10, 40, 11); // 定義一個 31列 x 2行 的窗口
textcolor(BLACK);
textbackground(WHITE);
cprintf("This is a test\r\n"); // 僅在窗口內顯示
getch();
return 0;
}
函數原型: int write(int fd, const void *buf, unsigned int count);
功能: 從緩衝區 buf 向文件描述符 fd 寫入最多 count 字節。返回實際寫入字節數,出錯返回 -1。
特點:
open/close/lseek 使用示例:
#include <fcntl.h>
#include <io.h>
#include <stdio.h>
#include <string.h>
#include <sys\stat.h>
int main(void) {
int handle;
char string[] = "Hello, world!\n";
int length = strlen(string);
if ((handle = open("TEST.$$$", O_WRONLY | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE)) == -1) {
printf("Error opening file.\n");
return 1;
}
int res = write(handle, string, length);
if (res != length) {
printf("Error writing to file (written %d of %d bytes).\n", res, length);
close(handle);
return 1;
}
printf("Wrote %d bytes to file.\n", res);
close(handle);
return 0;
}
開發提示:
wherex/wherey/window:屬於 Borland/Turbo C 風格的 conio.h 擴展,標準 C 不包含。Windows 下 Visual C++ 需引入 conio.h 並鏈接舊版庫,或使用 Windows Console API (GetConsoleScreenBufferInfo, SetConsoleWindowInfo) 實現同等功能。write:POSIX 標準系統調用封裝,Linux/Unix/macOS 直接可用。Windows 下 _write (需 io.h) 對應相同功能。高性能、大數據量 I/O 時優於 fwrite (無用戶態緩衝開銷),但需自行實現緩衝策略。ncurses (Unix) / PDCurses (跨平台) 或 FTXUI (C++17+) 等庫。