Is there a way to check how many bytes are available to be read?

I’ve been working on some stuff involving the Win32 API and Serial communications. I’ve managed to figure out how to open a COM port, and write/read to and from it, but I was wondering if there’s a way to see how many bytes and/or characters are available to be read.
I was thinking maybe the GetFileSizeEx() function would work, but it doesn’t seem like it.

I’m not entirely sure this question is very clear (as to what I’m looking for) so just to give a more obvious example, I’m hoping to find something like the Arduino’s Serial.available() function

Here’s my code thus far

#include <Windows.h>
#include <iostream>
#include <string>

int main() {
    HANDLE hFile;
    hFile = CreateFile("COM4",
        GENERIC_READ | GENERIC_WRITE,
        0,
        0,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        0);

    if(hFile == INVALID_HANDLE_VALUE) {
        std::cout << "bad handle" << std::endl;
        return 0;
    }
    DCB cerialParams = {0};
    cerialParams.DCBlength = sizeof(cerialParams);
    if(!GetCommState(hFile, &cerialParams)) {
        // error, but I'm too lazy to handle it.
        return 0;
    }

    cerialParams.BaudRate = CBR_9600;
    cerialParams.ByteSize = 8;
    cerialParams.StopBits = ONESTOPBIT;
    cerialParams.Parity = NOPARITY;

    if(!SetCommState(hFile, &cerialParams)) {
        // read above
        return 0;
    }

    COMMTIMEOUTS timeouts = {0};
    timeouts.ReadIntervalTimeout = 500;
    timeouts.ReadTotalTimeoutConstant = 500;
    timeouts.ReadTotalTimeoutMultiplier = 10;

    timeouts.WriteTotalTimeoutConstant = 500;
    timeouts.WriteTotalTimeoutMultiplier = 10;

    if(!SetCommTimeouts(hFile, &timeouts)) {
        // do it again
        return 0;
    }
    
    BOOL success = 0;
    PLARGE_INTEGER fSizeStruct{0};
    //I've noticed that after I try to run this function, printing to the console no longer seems to work, oh well.
    success = GetFileSizeEx(hFile, fSizeStruct);
    std::cout << '"' << fSizeStruct << '"' << std::endl;
    std::cout << success;

    CloseHandle(hFile);
    return 0;
}

>Solution :

You can use the ClearCommError() function:

Retrieves information about a communications error and reports the current status of a communications device.

The COMSTAT struct it fills in has a cbInQue member:

The number of bytes received by the serial provider but not yet read by a ReadFile operation.

Related/duplicate (in Delphi, but still applies here):

Get the count of bytes waiting on a serial port before reading

Leave a Reply