Как записать и прочитать данные с COM port на C(Си)

Всем привет, столкнулся с проблей, точнее неизвестной мне ошибкой. Хочу в выбранный ком порт записать какой ни-будь символ и прочитать его. Код прилагаю, помогите пожалуйста.

// ConsoleApplicationCOM.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <Windows.h>
#include <locale.h>

int _tmain(int argc, _TCHAR* argv[])
{
    struct
    {
        HANDLE h;
        TCHAR str[256];

    } Port[10];
    HANDLE htmp;
    DWORD err;
    DWORD res;
    DWORD portnum;
    TCHAR emsg[255];
    TCHAR cUser[255];
    //TCHAR sUser[255];

    _tsetlocale(LC_ALL, _T("ru-RU"));

    for (int i = 0; i != 10; i++)
    {

    while (1)
    {
        _tprintf(_T("\n Режим:\n 1 - Порты 0-9\n 2 - индивидуально\n 3 - Работать с ПОРТом\n q - Выход\n"));
        _getts(cUser);

        if (cUser[0] == _T('1'))
        {
            _tprintf(_T("\n Порты 0-9\n"));
            _tprintf(_T("\n 1 - ОТКРЫТЬ\n 2 - ЗАКРЫТЬ\n \n"));
            _getts(cUser);
            if (cUser[0] == _T('1'))
            {
                _tprintf(_T("\n ОТКРЫВАЕМ порты\n\n"));

                for (int i = 0; i != 10; i++)
                {
                    htmp =
                        CreateFile
                        (
                        Port[i].str,                    //_In_      LPCTSTR lpFileName,
                        GENERIC_READ | GENERIC_WRITE,   //_In_      DWORD dwDesiredAccess,
                        0,                              //_In_      DWORD dwShareMode,
                        0,                              //_In_opt_  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
                        OPEN_EXISTING,                  //_In_      DWORD dwCreationDisposition,
                        0,                              //_In_      DWORD dwFlagsAndAttributes,
                        0                               //_In_opt_  HANDLE hTemplateFile
                        );
                    
                    if (htmp != INVALID_HANDLE_VALUE) Port[i].h = htmp;
                    err = GetLastError();
                    FormatMessage
                        (
                        FORMAT_MESSAGE_FROM_SYSTEM,     //_In_      DWORD dwFlags,
                        0,                              //_In_opt_  LPCVOID lpSource,
                        err,                            //_In_      DWORD dwMessageId,
                        0,                              //_In_      DWORD dwLanguageId,
                        emsg,                           //_Out_     LPTSTR lpBuffer,
                        255,                            //_In_      DWORD nSize,
                        0                               //_In_opt_  va_list *Arguments
                        );
                    _tprintf(_T("PORT %s err=%d  h=0x%08X %s \n"), Port[i].str, err, (DWORD)Port[i].h, emsg);

                }
            }
            if (cUser[0] == _T('2'))
            {
                _tprintf(_T("\n ЗАКРЫВАЕМ порты \n\n"));
                

                for (int i = 0; i != 10; i++)
                {
                    
                    res = CloseHandle(Port[i].h);
                    
                    _tprintf(_T("CLOSE %s res=%d  h=0x%08X \n"), Port[i].str, res, (DWORD)Port[i].h);
                    
                    //_tprintf(_T("CLOSE %s h=0x%08X res=%d\n"), Port[i].str, (DWORD)Port[i].h, res);
                }
            }
            continue;
        }
        if (cUser[0] == _T('2'))
        {
            while (1)
            {
                _tprintf(_T("\n Номер порта? q for continue\n"));
                _getts(cUser);// = _gettch();
                if (cUser[0] == _T('q'))
                {
                    break;
                }
                
                portnum = _tstoi(cUser);
                _tprintf(_T("\n Порт %s\n"), Port[portnum].str);
                _tprintf(_T("\n 1 - ОТКРЫТЬ\n 2 - ЗАКРЫТЬ\n\n"));
                _getts(cUser);
                if (cUser[0] == _T('1'))
                {
                    htmp = CreateFile
                        (
                            Port[portnum].str,                  //_In_      LPCTSTR lpFileName,
                            GENERIC_READ | GENERIC_WRITE,   //_In_      DWORD dwDesiredAccess,
                            0,                              //_In_      DWORD dwShareMode,
                            0,                              //_In_opt_  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
                            OPEN_EXISTING,                  //_In_      DWORD dwCreationDisposition,
                            0,                              //_In_      DWORD dwFlagsAndAttributes,
                            0                               //_In_opt_  HANDLE hTemplateFile
                        );
                    if (htmp != INVALID_HANDLE_VALUE) Port[portnum].h = htmp;
                    err = GetLastError();
                    FormatMessage
                        (
                            FORMAT_MESSAGE_FROM_SYSTEM,     //_In_      DWORD dwFlags,
                            0,                              //_In_opt_  LPCVOID lpSource,
                            err,                            //_In_      DWORD dwMessageId,
                            0,                              //_In_      DWORD dwLanguageId,
                            emsg,                           //_Out_     LPTSTR lpBuffer,
                            255,                            //_In_      DWORD nSize,
                            0                               //_In_opt_  va_list *Arguments
                        );
                    _tprintf(_T("PORT %s err=%d  h=0x%08X %s \n"), Port[portnum].str, err, (DWORD)Port[portnum].h, emsg);
                }
                if (cUser[0] == _T('2'))
                {
                    res = CloseHandle(Port[portnum].h);
                    _tprintf(_T("CLOSE %s res=%d  h=0x%08X \n"), Port[portnum].str, res, (DWORD)Port[portnum].h);
                }
                
            }
            continue;
        }
        if (cUser[0] == _T('3'))
        {

            while (1)
            {
                _tprintf(_T("\n Номер порта? q for continue\n"));
                _getts(cUser);// = _gettch();
                if (cUser[0] == _T('q'))
                {
                    break;
                }

                portnum = _tstoi(cUser);
                _tprintf(_T("\n Порт %s\n"), Port[portnum].str);
                _tprintf(_T("\n 1 - Записать\n 2 - Прочитать\n\n"));
                _getts(cUser);

                if (cUser[0] == _T('1'))
                {
                    int nw = WriteFile
                        (
                            Port[portnum].str,   //_In_         HANDLE hFile,
                            "1",                 //_In_         LPCVOID lpBuffer,
                            1,                  //_In_         DWORD nNumberOfBytesToWrite,
                            0,                  //_Out_opt_    LPDWORD lpNumberOfBytesWritten,
                            0                   //_Inout_opt_  LPOVERLAPPED lpOverlapped
                        );
                    if (nw < 0)
                    {
                        _tprintf(_T("\nError:\n"));
                        return 0;
                    }
                }

                if (cUser[0] == _T('2'))
                {
                    char buff[32];
                    memset(&buff, '\0', sizeof(buff));

                    int nr = 0;
                    int spot = 0;
                    char ch = '\0';
                    do
                    {
                        nr = ReadFile
                            (
                                Port[portnum].str,   //_In_         HANDLE hFile,
                                &ch,                // _Out_        LPVOID lpBuffer,
                                1,                  // _In_         DWORD nNumberOfBytesToRead,
                                0,                  // _Out_opt_    LPDWORD lpNumberOfBytesRead,
                                0                   //  _Inout_opt_  LPOVERLAPPED lpOverlapped
                            );
                        if (nr < 0)
                        {
                            int er = errno;
                            _tprintf(_T("\nError:\n"));
                            return 0;
                        }
                        _tprintf(&buff[spot], "%c", ch);
                        spot += nr;
                    }
                    
                    while (ch != '\r' && nr > 0);


                    res = CloseHandle(Port[portnum].h);
                    _tprintf(_T("CLOSE %s res=%d  h=0x%08X \n"), Port[portnum].str, res, (DWORD)Port[portnum].h);

                    return 0;
                }

            }
            continue;
        }
        if (cUser[0] == _T('q')) break;
    }
    
    //_tprintf(_T("\n Press any key for exit\n"));
    //_gettch();//      getchar();
    return 0;
}

Ответы (0 шт):