Unix程序设计:实现cp命令

最近苦读《Unix系统编程》便写了一些实例,逐步增加自己Unix程序设计的能力。

首先来实现一个Unix下常用命令:cp

先看代码:


#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操作,既然不复杂,我就不解释了。

本代码再FreeBSD5.3下编译通过。


Author: heiyeluren
Date: 2005-08-02

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值