C++ std::ifstream for com port

Boyd Mills 0 Reputation points
2021-06-16T19:52:37.33+00:00

Never mind that the code doesn't do much. It fails on " comport.open("COM6:", std::ifstream::in);" with a nondescript error message.

Should I be able to use ifstream to open a com port? If not what is best practice in c++?

    std::ifstream comport;
    std::string linein;

    std::ios_base::iostate exceptionMask = comport.exceptions() | std::ios::failbit;
    comport.exceptions(exceptionMask);
    try 
    {
        comport.open("COM6:", std::ifstream::in);
    }
    catch (std::ios_base::failure &e) 
    {
        std::string erroropen( e.what() );
    }
    while (comport.is_open() )
    {
        std::getline(comport, linein);

    }
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,685 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Sam of Simple Samples 5,541 Reputation points
    2021-06-16T21:30:59.757+00:00

    Note that std::ifstream opens files. Note that the article Configuring a Communications Resource that DavidLowndes-6766 references uses CreateFile. Serial ports are devices. You must open them as a device. CreateFile is the Windows function for opening files and devices. I do not know for sure that none of the Standard C++ classes can be used for devices but probably none of them can. Also, it is not possible to use streaming with a device such as a serial port.

    See Serial Communications. It is old but still relevant. You might need to spend a month learning how to do serial communications. The following are more articles that might help.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.