CreateFile returns an INVALID_HANDLE_VALUE error (for a COM port), and GetLastError returns "cannot find the specified file"

I open the port to communicate with the device and control the device, but the function CreateFile()returns INVALID_HANDLE_VALUE.

GetLastError()returns 2, which means that it cannot find the specified file.

My code is shown below:

wsprintf( szPort, "COM%d", nPort );
m_hIDComDev = CreateFile(szPort,
                         GENERIC_READ | GENERIC_WRITE, 
                         0, 
                         NULL, 
                         OPEN_EXISTING, 
                         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 
                         NULL);
if (m_hIDComDev == INVALID_HANDLE_VALUE)
{
    DWORD err=GetLastError();
}

Why is this problem occurring?

+5
source share
2 answers

The problem is that you are not specifying the correct value lpFileNamefor your serial port. You should use this format:

"\\\\.\\COM%d"

This will result in a line that looks like \\.\COM1which is the correct format.

+6
source

char *szPort = _T("COM1"); // Change port number to your unused existing port

_T szPort ASCII.

+1

All Articles