小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

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

 accesine 2005-08-03

最近苦讀《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ò)。

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

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多