最近苦读《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下编译通过。
|