电竞比分网-中国电竞赛事及体育赛事平台

分享

unix程序設(shè)計:實現(xiàn)cp命令 - heiyeluren的blog

 accesine 2005-08-03

最近苦讀《Unix系統(tǒng)編程》便寫了一些實例,逐步增加自己Unix程序設(shè)計的能力。

首先來實現(xiàn)一個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);
 /* 打開目標(biāo)文件 */
 if ((outfile = open(name2, O_WRONLY|O_CREAT|O_TRUNC, PERM)) == -1)
 {
  close(infile);
  return (-2);
 }
 /* 循環(huán)的把源文件寫入目標(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;
 /* 進行復(fù)制 */
 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>

能夠復(fù)制任何文件,不管是ASC還是二進制的。其實根本原理就是調(diào)用了三個Unix下的系統(tǒng)調(diào)用:open, read, write,完成基本的IO操作,既然不復(fù)雜,我就不解釋了。

本代碼再FreeBSD5.3下編譯通過。

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多