系统调用实现文件复制

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>

#define BUFFER_SIZE 1024  //缓冲区大小


//实现文件内容的复制
int main(int argc,char ** argv)
{

    int from,to_fd;    //文件,复制文件
    int byte_read,byte_write;    //读的字节,写的字节数
    char buffer[BUFFER_SIZE];    //缓冲区
    char *ptr = NULL;	//解决部分写的问题(不全的问题)
    int ret;	//返回值
    if(3!=argc) //判断,3原文件,命令,目标文件,
    {
	printf("需要原文件和目标文件!\n");
        exit(0);    //-1为功能出错
    }
    
    from=open(argv[1],O_RDONLY);	//读原文件,不需要创建新文件
    
    if(-1 == from)
    {
	perror("打开原文件错误!\n");
        exit(-1);    //功能性错误
    }

    if((to_fd = open(argv[2],O_WRONLY | O_CREAT,S_IWUSR | S_IRUSR | S_IRGRP))== -1)
    {
	perror("打开文件错误!\n");
        close(from);
        exit(-1);
    }
    
    while(byte_read = read(from,buffer,BUFFER_SIZE))	//实现功能:读、EOF功能(部分读)
    {
	if(-1 == byte_read)
        {
	    perror("读取文件错误,复制失败!\n");
	    break;
        }
	else if(byte_read > 0)
	{
	    ptr = buffer;
	    while(byte_write = write(to_fd,ptr,byte_read))		//读多少,写多少,长度为byte_read
	    {
		if(-1 == byte_write)
		{
		    perror("写入文件错误,复制失败\n");
		    break;
		}
		else if(byte_write == byte_read)
		{
		    break;
		}
		else
		{
		    byte_read = byte_read - byte_write;
		    ptr = ptr +byte_write;
		}
	    }
	    if(-1 == byte_write)
	    {
		break;
	    }
	}
    }

    close(from);
    close(to_fd);


    return 0;
}

 若两文件不在同一文件夹下

阻塞请求:A调用B ,A一直等着B的返回,别的事情什么也不干。
非阻塞请求:A调用B,A不用一直等着B的返回,先去忙别的事情了。

posted on 2022-02-25 15:08  慧茗子  阅读(26)  评论(0)    收藏  举报  来源