Visual c++ operation of swprintf
Visual c++ operation of swprintf
我有一个例程,我称之为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
和数字之间没有空格。
相关文章:
- Usages of std::move
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 具有变量Number of Arguments的std::函数的矢量
- Capacity of a deque
- Deprecation of _writeBarrier()
- constexpr begin of a std::array
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- C++ "error: invalid use of void expression"
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- 赛通"Cannot take address of memoryview slice"
- C++ Version Of Double.longBitsToDouble
- 收到错误"invalid use of non-static data member 'stu::n' "
- C++ Usage of AsyncCallback
- 错误:"Left of getValue must have class/struct/union"
- Centos7 g++ "to_string is not in a member of std"
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- 传递 std::vector of std::shared_ptr,而不是更新对象
- C++/SDL "initial value of reference to a non-const must be an lvalue"
- Visual c++ operation of swprintf