利用标准I/O实现copy函数

/*使用标准I/O 实现copy函数*/

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

int main(int argc,char **argv)
{
    FILE *fd_fir;
    FILE *fd_sec;    //宏定义

    int x,y;
    char buff[1024];

    fd_fir = fopen(argv[1],"r");    //只读方式打开fd_fir
    fd_sec = fopen(argv[2],"a+");    //读写方式打开fd_sec

    if(fd_sec == NULL || fd_fir == NULL)    //判断两个文件是否为空
    {
        perror("fopen()");
        exit(1);
    }

while(1)    //利用循环一直复制数据
{
    
    memset(buff,0,sizeof(buff));    //每次赋值前清空缓存

    x = fread(buff,1023,1,fd_fir);    //读取需要复制的文件
    y = fwrite(buff,1023,1,fd_sec);    //写入到需要写入的文件

    if(feof(fd_fir))    //判断是否到达文件末尾
    {
        printf("copy completed.\n");
        break;
    }
    else if(ferror(fd_fir))    //判断是否出现错误
    {
        perror("error\n");
        break;
    }

}

fclose(fd_sec);
fclose(fd_fir);    //完成后关闭文件
    
return 0;
}

猜你喜欢

转载自blog.csdn.net/lovelijiapu/article/details/81409198