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