Linux下的C语言编程——系统调用read和write函数实现文件拷贝



系统调用read和write函数实现文件拷贝


#include 
#include 
#include 
#include 
#include 
#include 

#define SIZE 1024

int main()
{
	int from_fd;
	int to_fd;

	int nread;
	int nwrite;

	char buff[SIZE];
	char *ptr;

	if(argc != 3)
	{
		fprintf(stderr,"Usage: %s fromfile tofile\n\a",argv[0]);
		exit(-1);
	}

	if((from_fd = open(argv[1],O_RDONLY)) == -1)
	{
		fprintf(stderr,"open %serror: %s\n",argv[1],strerror(errno));
		exit(-1);
	}
	
	if((to_fd = open(argv[2],O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR)) == -1)
	{
		fprintf(stderr,"open %serror: %s\n",argv[2],strerror(errno));
		exit(-1);
	}

	while(nread = read(from_fd,buffer,SIZE))
	{
		if((nread == -1) && (errno != EINTR))
		{
			break;
		}
		else
			if(nread > 0)
			{
				ptr = buffer;

				while(nwrite = write(to_fd,ptr,nread))
				{
					if((nwrite == -1) && (errno != EINTR))
					{
						break;
					}
					else
						if(nwrite == nread)
						{
							break;
						}
						else
							if(n_write > 0)
							{
								ptr += nwrite;
								nread -= nwrite;
							}
				}

				if(nwrite == -1)
				{
					break;
				}

			}
	}

	close(from_fd);
	close(to_fd);
	exit(0);

    return 0;
}

你可能感兴趣的:(Linux下C语言基础编程)