1

Header

#pragma once

#include <windows.h>
#include <iostream>
#include <stdlib.h>
#include <WinBase.h>

using namespace std;

class SerialPort {
    public:
        BOOL COM_exists(int port);
};

cpp

#include "stdafx.h"
#include <string.h>
#include "SerialPort.h"

using namespace std;

BOOL SerialPort::COM_exists(int port)
{
    char buffer[7];
    COMMCONFIG CommConfig;
    DWORD size;

    if (!(1 <= port && port <= 255))
    {
        return FALSE;
    }

    snprintf(buffer, sizeof buffer, "COM%d", port);
    size = sizeof CommConfig;

    // COM port exists if GetDefaultCommConfig returns TRUE
    // or changes <size> to indicate COMMCONFIG buffer too small.
    return (GetDefaultCommConfig(L"buffer", &CommConfig, &size)
        || size > sizeof CommConfig);
}

main

#include "stdafx.h"
#include <iostream>
#include "SerialPort.h"

using namespace std;


if(num==1)
    {
        int i;
        for (i = 1; i < 256; ++i)
        {
            if (COM_exists(i))
            {
                cout <<"COM%d \n";
            }
        }
    }

I want listing serial ports on Windows ,but I'm having a hard time. Help me list the serial ports. error code = c3861 ,e0020

I want listing serial ports on windows. The end of the road ,Select a serial port that can be connected to enable communication. please help me

taek9105
  • 5
  • 2
  • Reopened because the suggested duplicate did not deal with the issues in the posted code (which have nothing to do with COM ports). – john Nov 09 '22 at 08:05

1 Answers1

0

Main problem is here

if(num==1)
    {
        int i;
        for (i = 1; i < 256; ++i)
        {
            if (COM_exists(i))
            {
                cout <<"COM%d \n";
            }
        }
    }

In C++ code has to go in functions (a simplification but good enough for now) and the program starts with a special function called main. Also cout <<"COM%d \n"; is not the correct way to print a COM port, I've used the correct way in the code below. Also in the code above what is num supposed to be?

Anyway rewrite as follows and you're a little closer

    int main() // start of program
    {
        int i;
        for (i = 1; i < 256; ++i)
        {
            if (COM_exists(i))
            {
                cout << "COM " << i << "\n";
            }
        }
    }

There are other problems such as the pointless SerialPort class. I would just remove that.

Replace

class SerialPort {
    public:
        BOOL COM_exists(int port);
};

with

BOOL COM_exists(int port);

and

BOOL SerialPort::COM_exists(int port)

with

BOOL COM_exists(int port)

The code looks like you are trying to learn C++ by cutting and pasting code from the internet. That is never going to work, C++ is a complex language and really needs formal study to be learned effectively. Here's a curated list of C++ books.

john
  • 85,011
  • 4
  • 57
  • 81