cp命令的介绍与实现

名称cp

使用权限 所有使用者

使用方式 cp [options] source dest

             cp [options] source... directory

说明将一个档案拷贝至另一档案或将数个档案拷贝至另一目录把计

-a 尽可能将档案状态权限等资料都照原状予以复制

-r 若 source 中含有目录名则将目录下之档案亦皆依序拷贝至目的地

-f 若目的地已经有相同档名的档案存在则在复制前先予以删除再行复制

范例

     将档案 aaa 复制(已存在)并命名为 bbb : cp aaa bbb

     将所有的C语言程式拷贝至 Finished 子目录中 : cp *.c Finished

 

实现

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>#define BUFSIZE  512
#define PERM  0755/* copy file function */
int copyfile(const char *name1, const char *name2)
{
 int infile, outfile;
 ssize_t nread;
 char buffer[BUFSIZE];
 /* 打开源文件 */
 if ((infile = open(name1, O_RDONLY)) == -1)
  return (-1);
 /* 打开目标文件 */
 if ((outfile = open(name2, O_WRONLY|O_CREAT|O_TRUNC, PERM)) == -1)
 {
  close(infile);
  return (-2);
 }
 /* 循环的把源文件写入目标文件 */
 while ((nread = read(infile, buffer, BUFSIZE)) > 0)
 {
  if (write(outfile, buffer, nread) < nread)
  {
   close(infile);
   close(outfile);
   return (-3);
  }
 }
 /* 关闭资源 */
 close(infile);
 close(outfile);
 
 if (nread == -1)
  return (-4);
 else
  return (0);
}main(int argc, char *argv[])
{
 /* 判断提交的参数 */
 if (argc != 3) {
  printf('Usage: copyfile <file1> <file2>/n');
  exit(1);
 }
 char *file1, *file2;
 file1 = argv[1];
 file2 = argv[2];
 int retcode;
 /* 进行复制 */
 retcode = copyfile(file1, file2);
 /* 错误信息控制 */
 if (retcode == -1) {
  printf('Open %s failed/n', file1);
  exit(1);
 }
 if (retcode == -2) {
  printf('Open %s failed/n', file2);
  exit(1);
 }
 if (retcode == -3) {
  printf('Read %s buffer failed/n', file1);
  exit(1);
 }
 if (retcode == -4) {
  printf('Write %s buffer failed/n', file2);
  exit(1);
 } if (retcode == 0) {
  printf('Copy file succeed!/n');
 }
}
保存为copyfile.c,然后使用gcc来编译:gcc -o copyfile copyfile.c使用命令的格式是:copyfile <file1> <file2>能够复制任何文件,不管是ASC还是二进制的。其实根本原理就是调用了三个Unix下的系统调用:open, read, write,完成基本的IO操作

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值