名称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操作