C++ – How to open COMXX files(serial port)

cserial-portwinapi

I've problem with serial port.

I've written a program that can read ports COM1 to COM9, but can open COMXX(like com10, com11, etc.)

I've searched and learnt that tCOM1–COM9 are part of the reserved names in the NT namespaces.
it says that "To acces files like COMXX you need to write "\.\COMXX".

I've tried this, but didn't make it.

Does anybody have an idea?
My best regards…

The code below return an invalid handle value because of this problem:

myPort = CreateFile("\\.\COM14",
              GENERIC_READ | GENERIC_WRITE,
              0,    /* exclusive access  */
              NULL, /* no security attrs */
              OPEN_EXISTING,
              0,
              NULL );

Best Answer

You need to escape the backslashes in the filename parameter:

myPort = CreateFile("\\\\.\\COM14",
              GENERIC_READ | GENERIC_WRITE,
              0,    /* exclusive access  */
              NULL, /* no security attrs */
              OPEN_EXISTING,
              0,
              NULL );

You're also trying to open COM port 14. Do you really have 14 COM ports on your machine? Try COM1 instead.

Related Topic