Visual c++ operation of swprintf

Visual c++ operation of swprintf

本文关键字:swprintf of operation c++ Visual      更新时间:2023-10-16

我有一个例程,我称之为swprintf。 从我找到的所有文档中,它应该像sprintf一样工作,只与Unicode字符串一起工作。 但是,代码

swprintf(buffer, wcslen(buffer), L"COM %d", i );

删除由 i 确定的字母数。 如果 i = 0 缓冲区 = "COM0";如果 i = 1,缓冲区 = "COM";如果 i = 2,缓冲区 = "CO" - 依此类推。

有人有解释吗??? 完整代码如下所示

void SelectComPort() //added function to find the present serial 
{
wchar_t lpTargetPath[5000]; // buffer to store the path of the COMPORTS
wchar_t buffer[20];
DWORD test;
bool gotPort=0; // in case the port is not found
size_t  size = 0;
for(int i=0; i<255; i++) // checking ports from COM0 to COM255
{
    swprintf(buffer, wcslen(buffer), L"COM %d", i );
    test = QueryDosDevice(buffer, &lpTargetPath[size], 5000);
        // Test the return value and error if any
    if(test != 0) //QueryDosDevice returns zero if it didn't find an object
    {
        size = wcslen(lpTargetPath);
        gotPort=1; // found port
    }
    if(::GetLastError()==ERROR_INSUFFICIENT_BUFFER)
    {
        lpTargetPath[10000]; // in case the buffer got filled, increase size    of the buffer.
        continue;
    }
}
return;

}

>swprintf缓冲区的长度作为参数,而不是字符串的长度。 wsclen在缓冲区中遇到空字符后将返回。 在未初始化的缓冲区上调用wcslen绝对是未定义的行为,因为指针很有可能在搜索终止 null 时从数组边界外递增。

不要调用wcslen,而是使用数组本身的长度,即 20。

另外:COM#端口在COM和数字之间没有空格。