#define MAX 500
char _readbuf[MAX];
while (read(socket_fd, _readbuf, MAX) > 0)
{
printf("%s", _readbuf);
if (strlen(_readbuf) < MAX) // 我用这种方式来判断是否读完
break;
memset(_readbuf, 0, MAX);
}
但是如果网速慢或者对方主机当掉的话,这样又读不完整了,就是不会一次性发满给你,分一点点发,那我这样判断是否读完又不行了。请问用read函数怎么实现完整读完对方发来的数据?
再具体一点,我在实现一个ftp客户端,比如我向服务端发送一个HELP命令,服务器会返回一串字符串的,结尾肯定是\r\n,但不保证\r\n出现一次,是否能判断逻辑读完?其实我就是不知道如何判断read是否完整读完。因为它就是返回一个字符串,能用EOF判断吗?
根据read的返回值判断:
size = read(somefd, someBuffer, length);
size > 0 //size就是实际读到的长度
size == 0 //读到eof了,读取结束
size < 0 //发生错误,要检查errno
man 2 read:
RETURN VALUE
On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, -1 is returned, and errno is set appropriately. In this case, it is left unspecified whether the file position (if any) changes.