Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read exactly one line?

I have a Linux file descriptor (from socket), and I want to read one line. How to do it in C++?

like image 730
Łukasz Lew Avatar asked Oct 17 '09 22:10

Łukasz Lew


2 Answers

I you are reading from a TCP socket you can't assume when the end of line will be reached. Therfore you'll need something like that:

std::string line;
char buf[1024];
int n = 0;
while(n = read(fd, buf, 1024))
{
   const int pos = std::find(buf, buf + n, '\n')
   if(pos != std::string::npos)
   {
       if (pos < 1024-1 && buf[pos + 1] == '\n')
          break;
   }
   line += buf;
}

line += buf;

Assuming you are using "\n\n" as a delimiter. (I didn't test that code snippet ;-) )

On a UDP socket, that is another story. The emiter may send a paquet containing a whole line. The receiver is garanted to receive the paquet as a single unit .. If it receives it , as UDP is not as reliable as TCP of course.

like image 83
yves Baumes Avatar answered Sep 18 '22 09:09

yves Baumes


Pseudocode:

char newline = '\n';
file fd;
initialize(fd);
string line;
char c;
while( newline != (c = readchar(fd)) ) {
 line.append(c);
}

Something like that.

like image 32
echo Avatar answered Sep 21 '22 09:09

echo