COPY.C:
#include <stdio.h>#include<unistd.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<string.h>//a.out src.txt dest.txt//argv[0] argv[1] argv[2]intMainintargcChar*argv[]) { Charsrc[ -] = {0}; Chardest[ -] = {0}; intFDR; intFDW; intret; Charbuf[1024x768] = {0}; if(ARGC! =3) {printf ("Usage:%s src.txt dest.txt\n", argv[0]); return-1; } strcpy (src,argv[1]); strcpy (dest,argv[2]); /*1. Open the source file in the way Src.txt*/FDR=open (src,o_rdonly); if(FDR <0) {perror ("Open"); return-1; } /*2. Open the target file Dest.txt in writing, and if it does not exist, create*/FDW= Open (Dest,o_wronly | O_creat,0755); if(FDW <0) {perror ("Open"); return-1; } /*3. Move the src file pointer to the file header*/Lseek (FDR,0, Seek_set); /*3. Loop the read src.txt until the end*/ while(1) {memset (buf,0,sizeof(BUF));//Qing 0ret = Read (FDR,BUF,sizeof(BUF)-1); if(Ret >0){ /*4. Write the contents of the read to Dest.txt*/write (Fdw,buf,ret); }Else if(0==ret) { /*Read End*/printf ("Read over!\n"); Break; }Else{perror ("Read"); Break; } } /*5. Close*/Close (FDR); Close (FDW); return 0;}
File I/O implementation CP copy function