mycopyFile_linux下实现简单文件的复制

/*
*Author:
*Function: 实现简单文件的复制拷贝
*/


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

#define BUFFERSIZE 1024

int main(int argc,char *argv[])
{
int fd_read; //指向需要读的文件的filedes
int fd_write; //指向需要写入的文件的filedes
int ret_read; //read函数的返回值
int ret_write; //write函数的返回值
ssize_t ret; //read函数返回值
char buf[BUFFERSIZE]; //定义缓冲区


if(3 != argc) //命令行参数检测
{
printf("Usermsg:./copy <file a> <file b>\n");
exit (-1);
}

//只读的方式打开a文件,需要被拷贝的文件
fd_read = open(argv[1],O_RDONLY);
//返回值检查
if(fd_read < 0)
{
perror("open the file a:");
exit(-1);
}

//只读的方式打开b文件,需要拷贝的目标文件,设定权限为可读可写可执行
fd_write = open(argv[2],O_WRONLY | O_CREAT,0777);
//返回值检查
if(fd_write < 0)
{
perror("open the file b:");
exit(-1);
}


//进入循环读写操作
while((ret = read(fd_read,buf,BUFFERSIZE)) > 0)
{
if(write(fd_write,buf,ret) > 0)
{
continue;
}
else
{
break;
}

}


//关闭文件描述符
close(fd_read);
close(fd_write);
exit(0);

}


测试结果:

使用编译命令进行编译:gcc -o copy mycopyFile.c

./copy a.txt b.txt

a.txt必须是存在的文件,b.txt没有关系。

我在a.txt中的内容是hello,结果在b.txt中也复制了内容,hello。j结果正确。



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShaYQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值