nix::readLine: Add eofOk parameter

This commit is contained in:
Robert Hensing 2024-11-06 14:20:06 +01:00
parent 4a785a0400
commit f7b1e535a3
2 changed files with 13 additions and 4 deletions

View File

@ -77,8 +77,13 @@ void writeFull(Descriptor fd, std::string_view s, bool allowInterrupts = true);
/** /**
* Read a line from a file descriptor. * Read a line from a file descriptor.
*
* @param fd The file descriptor to read from
* @param eofOk If true, return an unterminated line if EOF is reached. (e.g. the empty string)
*
* @return A line of text ending in `\n`, or a string without `\n` if `eofOk` is true and EOF is reached.
*/ */
std::string readLine(Descriptor fd); std::string readLine(Descriptor fd, bool eofOk = false);
/** /**
* Write a line to a file descriptor. * Write a line to a file descriptor.

View File

@ -47,7 +47,7 @@ void writeFull(int fd, std::string_view s, bool allowInterrupts)
} }
std::string readLine(int fd) std::string readLine(int fd, bool eofOk)
{ {
std::string s; std::string s;
while (1) { while (1) {
@ -58,8 +58,12 @@ std::string readLine(int fd)
if (rd == -1) { if (rd == -1) {
if (errno != EINTR) if (errno != EINTR)
throw SysError("reading a line"); throw SysError("reading a line");
} else if (rd == 0) } else if (rd == 0) {
if (eofOk)
return s;
else
throw EndOfFile("unexpected EOF reading a line"); throw EndOfFile("unexpected EOF reading a line");
}
else { else {
if (ch == '\n') return s; if (ch == '\n') return s;
s += ch; s += ch;