mycopyFile_linux下实现简单文件的复制

来源:互联网 发布:hello kitty主题软件 编辑:程序博客网 时间:2024/05/21 22:44
/*
*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结果正确。



原创粉丝点击