高级IO,一次读取500000复制文件,输入输出流

#include "include/apue.h"
#include <errno.h>
#include <fcntl.h>


char buf[500000];


void set_fl(int fd,int flags) /* flags are file status flags to turn on */
{
    int        val;

    if ( (val = fcntl(fd,F_GETFL,0)) < 0)
        {
            printf("fcntl F_GETFL error");
            exit(1);
        }

    val |= flags;        /* turn on flags */

    if (fcntl(fd,F_SETFL,val) < 0)
        {
            printf("fcntl F_SETFL error");
            exit(1);
        }
}

void clr_fl(int fd,int flags)
{
    int val;

    if ((val = fcntl(fd,0)) == -1)
    {
//        syslog(LOG_ERR,__FILE__,__LINE__,"fcntl() error : %s",strerror(errno));
        exit(1);
    }
    val &= ~flags; /* turn flags off */

    if (fcntl(fd,val) == -1)
    {
//        syslog(LOG_ERR,strerror(errno));
        exit(1);
    }
    return;
}

int main()
{
	int ntowrite,nwrite;
	char *ptr;

	ntowrite = read(STDIN_FILENO,buf,sizeof(buf));
	fprintf(stderr,"read %d bytes\n",ntowrite);

	set_fl(STDOUT_FILENO,O_NONBLOCK);

	ptr = buf;

	while(ntowrite > 0)
	{
		errno = 0;
		nwrite = write(STDOUT_FILENO,ptr,ntowrite);
		fprintf(stderr,"nwrite = %d,errno = %d\n",nwrite,errno);

		if (nwrite > 0)
		{
			ptr += nwrite;
			ntowrite -= nwrite;
		}

	}

	clr_fl(STDOUT_FILENO,O_NONBLOCK);


	return 0;
}

执行:./a.out < /etc/services > temp.file

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐