Linux下C語言實現檔案拷貝 轉

2021-08-27 06:38:36 字數 1802 閱讀 1090

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*/

#include /**/

#include /*stderror()*/

#include /*open(),flag*/

#include /*errno*/

#include /*ssize_t*/

#include

#include /*mode_t*/

#define buffer_size 3

int main(int argc,char **argv)

int from_fd,to_fd;

int bytes_read,bytes_write;

char buffer[buffer_size];

char *ptr;

if(argc!=3)

fprintf(stderr,"usage:%s fromfile tofile\n\a",argv[0]);

exit(1);

/* 開啟原始檔 */

if((from_fd=open(argv[1],o_rdonly))==-1)   /*open file readonly,返回-1表示出錯,否則返回檔案描述符*/

fprintf(stderr,"open %s error:%s\n",argv[1],strerror(errno));

exit(1);

/* 建立目的檔案 */

/* 使用了o_creat選項-建立檔案,open()函式需要第3個引數,

mode=s_irusr|s_iwusr表示s_irusr 使用者可以讀 s_iwusr 使用者可以寫*/

if((to_fd=open(argv[2],o_wronly|o_creat,s_irusr|s_iwusr))==-1) 

fprintf(stderr,"open %s error:%s\n",argv[2],strerror(errno));

exit(1);

/* 以下**是乙個經典的拷貝檔案的** */

while(bytes_read=read(from_fd,buffer,buffer_size))

/* 乙個致命的錯誤發生了 */

if((bytes_read==-1)&&(errno!=eintr)) 

break;

else if(bytes_read>0)

ptr=buffer;

while(bytes_write=write(to_fd,ptr,bytes_read))

/* 乙個致命錯誤發生了 */

if((bytes_write==-1)&&(errno!=eintr))

break;

/* 寫完了所有讀的位元組 */

else if(bytes_write==bytes_read) 

break;

/* 只寫了一部分,繼續寫 */

else if(bytes_write>0)

ptr+=bytes_write;

bytes_read-=bytes_write;

/* 寫的時候發生的致命錯誤 */

if(bytes_write==-1)

break;

close(from_fd);

close(to_fd);

return;

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語言程式拷貝檔案

localhost login root password 登陸字元介面 root localhost root mkdir dir1 dir2 在root目錄下,分別建立dir1,dir2兩個資料夾 root localhost root ll 檢視剛建立的dir1,dir2資料夾 root lo...