封装read和write函数

int readn(int fd, void *vptr, int n)
{
	int nleft;
	int nread;
	char *ptr;

	ptr = (char*)vptr;
	nleft = n;

	while(nleft > 0)
	{
		nread = read(fd, ptr, nleft);
		if(nread < 0)
		{
			if(errno == EINTR)
				nread = 0;		/* and call read() again */
			else
				return -1;
		}
		else if(nread == 0)
		{
			break;	/*	EOF */
		}
		
		nleft -= nread;
		ptr   += nread;
	}
	return (n - nleft);
}

int writen(int fd, const void *vptr, int n)
{
	int nleft;
	int nwritten;
	const char *ptr;

	ptr = (const char *)vptr;
	nleft = n;

	while(nleft > 0)
	{
		nwritten = write(fd, ptr, nleft);
		if(nwritten <= 0)
		{
			if(nwritten < 0 && errno == EINTR)
				nwritten = 0;
			else
				return -1;
		}

		nleft -= nwritten;
		ptr   += nwritten;
	}

	return n;
}

你可能感兴趣的:(封装read和write函数)