cp命令的介紹與實現

名稱cp

使用權限 所有使用者

使用方式 cp [options] source dest

             cp [options] source... directory

說明將一個檔案拷貝至另一檔案或將數個檔案拷貝至另一目錄把計

-a 儘可能將檔案狀態權限等資料都照原狀予以複製

-r 若 source 中含有目錄名則將目錄下之檔案亦皆依序拷貝至目的地

-f 若目的地已經有相同檔名的檔案存在則在複製前先予以刪除再行復制

範例

     將檔案 aaa 複製(已存在)並命名爲 bbb : cp aaa bbb

     將所有的C語言程式拷貝至 Finished 子目錄中 : cp *.c Finished

 

實現

#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操作

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章