- printfex函数
函数用途: 在屏幕的任意位置, 输出任意颜色的带格式的字符串
函数原型: void printfex(int x, int y, int color, const char *str, ...);
int x, y, color: 同printex
const char *str: 输出的带格式字符串
...: 输出的变量
输出函数的修改版本. 可以像printf一样输出带格式的字符串, 而不需要先将文本经过sprintf处理一遍.
conlib.c
void printfex(int x, int y, int color, const char *str, ...)
{
char buf0[2048];
HANDLE hConsole;
va_list arg0;
va_start(arg0, str);
vsprintf(buf0, str, arg0);
va_end(arg0);
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
gotoXY(x, y);
SetConsoleTextAttribute(hConsole, color);
WriteConsole(hConsole, buf0, strlen(buf0), NULL, 0);
return;
}
在C语言里, 如果需要处理像printf一样不定量的参数, 则需要使用到stdarg.h头文件里面的相关函数.
va_list是一个处理不定量参数的变量格式. 在程序里, 先执行va_start函数初始化不定量参数表.
va_start的第一个参数是需要初始化的参数表, 第二个参数, 则是上级函数不定量参数的前一个参数. 这里指定的是str, va_start就会将str之后的参数(也就是...的内容)记录在arg0之中.
之后可以用va_arg函数来获得参数表里的参数. 这里我调用了vsprintf函数, 这个函数使用不定量参数表来替代sprintf后面的参数, 来实现对带格式的字符串的处理.
最后使用va_end函数释放不定量参数表.
之后的内容就和printex一样了. 但是向控制台输出文本这个步骤, 我使用了另外一个函数WriteConsole, 这是一个Windows API函数. 原型如下:
BOOL WINAPI WriteConsole(HANDLE hConsoleOutput, LPSTR lpBuffer, DWORD nNumberOfCharsToWrite, LPDWORD lpNumberOfCharsWritten, DWORD lpReserved);
hConsoleOutput就是控制台句柄, lpBuffer是字符串缓冲区, nNumberOfCharsToWrite表示需要输出的数据长度, 这里设置为字符串的长度, 即strlen的返回值.
nNumberOfCharsWritten是返回实际上输出数据长度的缓冲区, lpReserved是保留参数. 这两个参数我都设置为0.
这样就完成了.