1 #include<stdio.h> 2 3 int main(int argc,char *argv[]) 4 {
char buf[100]={0}; 5 if(argc<3){ 6 printf("参数输入错误 "); 7 return 0; 8 } 9 10 FILE *p_src = fopen(argv[1],"rb"); 11 if(!p_src){ 12 printf("读取文件失败 "); 13 return 0; 14 } 15 16 FILE *p_dst = fopen(argv[2],"wb"); 17 if(!p_dst){ 18 printf("写入文件失败 ", ); 19 fclose(p_src); 20 p_src = NULL; 21 return 0; 22 } 23 24 int size = 0; 25 while(1){ 26 size = fread(buf,sizeof(char),100,p_src); 27 if(!size) 28 break; 29 fwrite(buf,sizeof(char),size,p_dst); 30 } 31 32 fclose(p_dst); 33 p_dst = NULL; 34 fclose(p_src); 35 p_src = NULL; 36 37 }
还可以运用系统调用函数实现cat命令的功能:
1 #include <sys/types.h> 2 #include <sys/stat.h> 3 #include <fcntl.h> 4 #include<stdio.h> 5 #include<unistd.h> 6 #define MAXSIZE 4096 7 int main(int argc,char *argv[]) 8 { 9 char buf[MAXSIZE]; 10 size_t n = 0; 11 int fd = open(argv[1],O_RDONLY); 12 if(fd==-1){perror("open");return -1;} 13 14 while((n = read(fd,buf,MAXSIZE))>0){ 15 if(write(1,buf,n)!=n){ 16 printf("write error"); 17 return 0; 18 } 19 } 20 21 close(fd); 22 return 0; 23 }