Linux下程式(C語言)實現對檔案的複製

2021-09-05 10:25:09 字數 1370 閱讀 9512

目標: 使用系統呼叫實現cp命令。

原理: 使用系統呼叫open開啟檔案,使用read從檔案讀資料,使用write向檔案寫資料。

傳給可執行程式的引數個數存放在main函式的argc中,引數首位址存放在指標陣列argv中。

我的**1

#include #include #include #include #include int main(int argc,char *argv)

int fr = open(argv[1],o_rdonly,0777);

int fw = open(argv[2],o_wronly|o_creat,0777);

if(fr < 0)

if(fw < 0)

char str[20];

int count;

while((count = read(fr,str,20)) > 0)//每次讀取20個字元

close(fr);

close(fw);

return 0;

}

我的**2

#include#include#include#include#include#includeint main(int argc, char *argv)

fd_new = open(argv[2],o_rdwr|o_creat,0755);

if(fd_new<0)

lseek(fd,0,seek_set);

length = lseek(fd,0,seek_end);

buf = (char *)malloc(length+1);

lseek(fd,0,seek_set);

read(fd,buf,length);

write(fd_new,buf,length);

close(fd);

close(fd_new);

return 0;

}

老師給的**:

#include #include #include #include int main(int argc, char *argv)

fd_dest = open(argv[2], o_wronly|o_creat, 0755);

if(fd_dest < 0)

char buf[1024] = "";

dowhile(ret >0);

close(fd_src);

close(fd_dest);

} return 0;

}

Linux下C語言實現CopyFile

linux下c語言實現檔案拷貝 function copy file from file1 to file2 how to execute copyfile file1 file2 under linux data 2007 05 09 include fprintf stderr,bufsiz i...

Linux下C語言實現UDP Socket程式設計

該博文參考了linux c socket 程式設計之udp一文,在這裡表示感謝!傳送方 file udp sender.c author henry created on 2019年5月29日17 08 13 主要實現 傳送20個文字訊息,然後再傳送乙個終止訊息 include include in...

Linux下C語言實現簡單Shell

include include include include include include include include define max string 256 define signin define signout define signpine const char expst ex...