|
最近苦讀《Unix系統(tǒng)編程》便寫(xiě)了一些實(shí)例,逐步增加自己Unix程序設(shè)計(jì)的能力。
首先來(lái)實(shí)現(xiàn)一個(gè)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]; /* 打開(kāi)源文件 */ if ((infile = open(name1, O_RDONLY)) == -1) return (-1); /* 打開(kāi)目標(biāo)文件 */ if ((outfile = open(name2, O_WRONLY|O_CREAT|O_TRUNC, PERM)) == -1) { close(infile); return (-2); } /* 循環(huán)的把源文件寫(xiě)入目標(biāo)文件 */ while ((nread = read(infile, buffer, BUFSIZE)) > 0) { if (write(outfile, buffer, nread) < nread) { close(infile); close(outfile); return (-3); } } /* 關(guān)閉資源 */ close(infile); close(outfile); if (nread == -1) return (-4); else return (0); }
main(int argc, char *argv[]) { /* 判斷提交的參數(shù) */ if (argc != 3) { printf("Usage: copyfile <file1> <file2>\n"); exit(1); } char *file1, *file2; file1 = argv[1]; file2 = argv[2]; int retcode; /* 進(jìn)行復(fù)制 */ retcode = copyfile(file1, file2); /* 錯(cuò)誤信息控制 */ 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來(lái)編譯:gcc -o copyfile copyfile.c
使用命令的格式是:copyfile <file1> <file2>
能夠復(fù)制任何文件,不管是ASC還是二進(jìn)制的。其實(shí)根本原理就是調(diào)用了三個(gè)Unix下的系統(tǒng)調(diào)用:open, read, write,完成基本的IO操作,既然不復(fù)雜,我就不解釋了。
本代碼再FreeBSD5.3下編譯通過(guò)。
|