首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C語言標準庫函數速查:W 開頭函數詳解

     編輯:關於C語言

C語言標準庫函數速查:W 開頭函數詳解

W 開頭函數雖數量不多,但涵蓋了文本窗口座標查詢、窗口定義、底層文件寫入等關鍵功能,是控制台程序與底層 I/O 開發的常用工具。

文本窗口座標查詢 (conio.h)

wherex - 獲取當前窗口水平光標位置

函數原型: int wherex(void);

功能: 返回當前文本窗口內光標的 X 座標 (1-based,最左列為 1)。

wherey - 獲取當前窗口垂直光標位置

函數原型: 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;
}

文本窗口定義

window - 定義活動文本窗口區域

函數原型: 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;
}

底層文件寫入

write - 向文件描述符寫入數據

函數原型: int write(int fd, const void *buf, unsigned int count);

功能: 從緩衝區 buf 向文件描述符 fd 寫入最多 count 字節。返回實際寫入字節數,出錯返回 -1。

特點:

  • 無緩衝、直接調用系統調用
  • 需自行處理部分寫入 (返回值 < count)
  • 配合 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 (無用戶態緩衝開銷),但需自行實現緩衝策略。
  • 文本窗口概念在現代終端模擟器中已淡化,跨平台 TUI 開發建議使用 ncurses (Unix) / PDCurses (跨平台) 或 FTXUI (C++17+) 等庫。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved