利用linux提供的系统IO,来实现cp命令
分析:cp操作的两个参数是路径加文件名即路径名
1)注意拷贝的源文件不能更改,打开权限–>只读
2)拷贝的目的文件如果不存在需要创建后再拷贝,如果存在需要清空文件内容再拷贝(附图验证cp操作也是这样的)。
–>可写+截短+创建权限
将1.txt的内容拷贝到了2.txt(2.txt先前并不存在);将3.txt的内容拷贝到2.txt(2.txt的内容被清空)
难点:怎么判断拷贝完了!每次拷贝(读)规定大小的字节数,如果有一次读到的字节数少于规定的,那么一定拷贝完了!
输入格式: ./main src_pathname dest_pathname
把src_pathname文件拷贝到 dest_pathname文件验证:将cp.c的内容拷贝到了2.txt(2.txt先前并不存在);将1.txt的内容拷贝到2.txt(2.txt的内容被清空)
源码:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc,char *argv[])
{
int src_fd = open(argv[1], O_RDONLY);
if(src_fd == -1)
{
perror("open src_pathname error:");
return -1;
}
int dest_fd = open(argv[2], O_WRONLY | O_TRUNC|O_CREAT,0666);
if(dest_fd == -1)
{
perror("open dest_pathname error:");
return -1;
}
unsigned char buf[10] = {0};//读出来的数据保存到这里
while(1)
{
int ret = read(src_fd,buf,sizeof(buf));//buf这里代表整个数组
if(ret == -1)
{
perror("read error");
return -1;
}
write(dest_fd,buf,ret);
if(ret < sizeof(buf))
{
break;
}
}
close(src_fd);
close(dest_fd);
}