系統呼叫實現Linux命令 cp

2021-08-02 08:33:44 字數 1152 閱讀 2445

和命令ls一樣,我以前在網易上寫的搬過來,嘻嘻!

cp.c如下:

#include "cp.h"

//注意:計算完檔案大小後 要記得指標復位

//記得關閉檔案

void cp(char src_path_filename,char dest_path_filename)

/*以唯讀方式開啟原始檔*/

int fd_src = open(src_path_filename,o_rdonly);

/*計算原始檔大小*/

int file_size = lseek(fd_src,0,seek_end); //計算原始檔的大小

lseek(fd_src,0,seek_set); //原始檔指標復位

char buf[file_size]; //定義緩衝區來接收原始檔內容加乙個\0

/*讀取原始檔內容放入buf 並返回實際讀取位元組數*/

int read_size = read(fd_src,buf,file_size-1);//因為去掉\0 不減1會多乙個換行

if(-1 == read_size)

/*以讀寫方式開啟目標檔案 若檔案不存在 則建立目標檔案*/

int fd_dest = open(dest_path_filename,o_rdwr|o_creat);

/*將buf裡面的資料寫入到目標檔案中*/

if(-1 == write(fd_dest,buf,file_size-1))

/*關閉檔案*/

close(fd_src); //關閉原始檔

close(fd_dest); //關閉目標檔案

printf("copy succeed !\n");

}

main.c如下:

#include "alldef.h"

#include "cp.h"

/* * 功能:c語言實現 cp dir/filename dir/filename 命令(用系統呼叫)

* 日期:2015-08-06

*/int main(int argc,char *argv)

執行時:當前目錄下,./cp 源檔名 目標檔案

實現linux的cp命令

主要運用open 開啟檔案,運用read 讀出檔案的內容到緩衝區,write 將緩衝區的內容寫入新的檔案,來模擬實現linux命令的cp功能。注意可以通過使用lseek 函式來獲取檔案的大小。c語言實現linux cp命令 include open 所需標頭檔案 include lseek 所需標頭...

Linux命令 cp命令

cp命令用來複製檔案或者目錄,是linux系統中最常用的命令之一。1,語法 cp options source dest 或者cp options source.directory 2,引數說明 f 覆蓋已經存在的目標檔案而不給出提示。i 與 f選項相反,在覆蓋目標檔案之前給出提示,要求使用者確認是...

Linux命令之 cp命令》

cp命令用來複製檔案或者目錄,是linux系統中最常用的命令之一。一般情況下,shell會設定乙個別名,在命令列下複製檔案時,如果目標檔案已經存在,就會詢問是否覆蓋,不管你是否使用 i引數。但是如果是在shell指令碼中執行cp時,沒有 i引數時不會詢問是否覆蓋。這說明命令列和shell指令碼的執行...