如何准确地读一行? [英] How to read exactly one line?

查看:109
本文介绍了如何准确地读一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Linux文件描述符(来自套接字),我想读一行. 如何在C ++中做到这一点?

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

推荐答案

我是从TCP套接字读取的,因此无法假定何时到达行尾. 因此,您需要这样的东西:

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;

假设您使用"\ n \ n"作为分隔符. (我没有测试该代码段;-))

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

在UDP套接字上,这是另一回事了.发射者可以发送包含整条线的木条.接收方被保证可以作为单个单元来接收该模块.如果接收到该模块,则UDP当然不如TCP可靠.

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.

这篇关于如何准确地读一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆