linux网络编程中所用到的读写函数
程序员文章站
2022-03-02 18:06:01
...
#UNIX网络编程 卷一
ssize_t readn(int fd, void *buf, size_t count);
/**
*readn - 读取固定字节数
*@fd: 文件描述符
*@buf: 接收缓冲区
*@count: 要读取的字节数
* 成功返回count,失败返回-1,读到EOF返回<count
*/
ssize_t readn(int fd, void *buf, size_t count)
{
size_t
nleft = count;
ssize_t nread;
char *bufp = (char*)buf;
while(nleft > 0) {
if((nread = read(fd, bufp, nleft)) < 0) {
if(errno == EINTR)
continue;
return -1;
}
else if (nread == 0)
return count - nleft;
bufp+= nread;
nleft-= nread;
}
return count;
}
###ssize_t writen(int fd, const void *buf, size_t count);
/**
*writen - 发送固定字节数
*@fd: 文件描述符
*@buf: 发送缓冲区
*@count: 要读取的字节数
* 成功返回count,失败返回-1
*/
ssize_t writen(int fd, const void *buf,size_t count)
{
size_t nleft = count;
ssize_t nwritten;
char *bufp = (char*)buf;
while(nleft > 0) {
if((nwritten = write(fd, bufp, nleft)) < 0) {
if(errno == EINTR)
continue;
return-1;
}
else if (nwritten == 0)
continue;
bufp+= nwritten;
nleft-= nwritten;
}
return count;
}
###ssize_t recv_peek(int sockfd, void *buf, size_t len);
/**
*recv_peek - 仅仅查看套接字缓冲区数据,但不移除数据
*@sockfd: 套接字
*@buf: 接收缓冲区
*@len: 长度
* 成功返回>=0,失败返回-1
*/
ssize_t recv_peek(int sockfd, void *buf, size_t len)
{
while(1) {
int ret = recv(sockfd, buf, len, MSG_PEEK);
if(ret == -1 && errno == EINTR)
continue;
return ret;
}
}
###ssize_t readline(int sockfd, void *buf, size_t maxline);
/**
*readline - 按行读取数据
*@sockfd: 套接字
*@buf: 接收缓冲区
*@maxline: 每行最大长度
* 成功返回>=0,失败返回-1
*/
ssize_t readline(int sockfd, void *buf,size_t maxline)
{
int ret;
int nread;
char *bufp = buf;
int nleft = maxline;
while(1) {
ret = recv_peek(sockfd, bufp, nleft);
if(ret < 0)
return ret;
else if (ret == 0)
return ret;
nread = ret;
int i;
for(i=0; i<nread; i++) {
if(bufp[i] == '\n') {
ret= readn(sockfd, bufp, i+1);
if(ret != i+1)
exit(EXIT_FAILURE);
return ret;
}
}
if(nread > nleft)
exit(EXIT_FAILURE);
nleft -= nread;
ret= readn(sockfd, bufp, nread);
if(ret != nread)
exit(EXIT_FAILURE);
bufp+= nread;
}
return -1;
}
上一篇: Ubuntu使用所用到的
下一篇: Java获取项目中的路径