Unix程序设计:实现cp命令
来源:互联网 发布:读懂中国经济数据下 编辑:程序博客网 时间:2024/05/22 20:03
最近苦读《Unix系统编程》便写了一些实例,逐步增加自己Unix程序设计的能力。
首先来实现一个Unix下常用命令:cp
先看代码:
#include
#include
#include
#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
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
能够复制任何文件,不管是ASC还是二进制的。其实根本原理就是调用了三个Unix下的系统调用:open, read, write,完成基本的IO操作,既然不复杂,我就不解释了。
本代码再FreeBSD5.3下编译通过。
Author: heiyeluren
Date: 2005-08-02
- Unix程序设计:实现cp命令
- Unix程序设计:实现cp命令
- Unix程序设计:实现cp命令
- Unix程序设计:实现wc命令
- Unix程序设计:实现wc命令
- UNIX CP命令(转)
- cp命令实现
- cp命令的实现
- linux cp 命令实现
- cp命令的实现
- cp命令C实现
- linux命令实现:cp
- Linux 实现cp 命令
- linux 的cp命令实现
- linux cp 命令的实现
- 编程实现cp命令功能
- 简单cp命令的实现
- cp命令实现不覆盖
- JavaScript实际应用:innerHTMl和确认提示的使用
- 轻型数据库SQLite结合PHP的开发
- 关于TextOut输出的字符串透明的问题
- C++/CLI标准化工作告一段落![原文发表时间:2005年9月22日]
- 演练VC中的COMMON一族(转贴)之二
- Unix程序设计:实现cp命令
- 使用Apache的rewrite技术
- 2006年4月度国际标准化组织C++会议纪要[原文发表时间:2006年5月3日]
- 演练VC中的COMMON一族(转贴)之一
- 【Scott Meyers】C++5×5断想之五:我之C++拍案惊奇
- 学好VC++的十大良好习惯
- 关于CSocket类的Receive超时的问题
- PHP中模板分页的处理
- 【Scott Meyers】C++5×5断想之四:C++历史上最重要人物