I need to read the NMEA sentences from a GPS connected through UART. The OS is Debian, and the language must be C++. To do so I\'m opening the file with open(...)
a
I need to read the NMEA sentences from a GPS connected through UART.
...
How may I use read(...) and stop on new line?
If you opened a terminal device (e.g. /dev/ttyUSB0), then you can use the terminal's line discipline handler to parse the received text into lines.
The terminal must be opened in blocking mode (which is the default unless non-blocking is specified), and the terminal must be configured for canonical input (using the termios API).
Is there an option to read(...)?
When the terminal device is configured for canonical input, then a read() will return a line of text (unless an error occurred). Be sure that your read buffer (and count argument) is large enough for the longest expected line, so that the read() will not truncate the line.
From the termios man page:
Canonical and noncanonical mode
The setting of the ICANON canon flag in c_lflag determines whether
the terminal is operating in canonical mode (ICANON set) or
noncanonical mode (ICANON unset). By default, ICANON set.
In canonical mode:
* Input is made available line by line. An input line is available
when one of the line delimiters is typed (NL, EOL, EOL2; or EOF at
the start of line). Except in the case of EOF, the line delimiter
is included in the buffer returned by read(2).
* Line editing is enabled (ERASE, KILL; and if the IEXTEN flag is
set: WERASE, REPRINT, LNEXT). A read(2) returns at most one line
of input; if the read(2) requested fewer bytes than are available
in the current line of input, then only as many bytes as requested
are read, and the remaining characters will be available for a
future read(2).
* The maximum line length is 4096 chars (including the terminating
newline character); lines longer than 4096 chars are truncated.
After 4095 characters, input processing (e.g., ISIG and ECHO*
processing) continues, but any input data after 4095 characters up
to (but not including) any terminating newline is discarded. This
ensures that the terminal can always receive more input until at
least one line can be read.
Use the stty command, or tcgetattr() and tcsetattr() to configure the terminal mode.
Study Setting Terminal Modes Properly
and
Serial Programming Guide for POSIX Operating Systems.
Note that the line returned in the read buffer is not a string, and will not be terminated with a null byte. For a solution see Linux Serial Read throws Error