linux下用c库和系统调用实现文件的复制

时间:2022-02-06 21:02:52

c库:

#include <stdio.h>

 

int main(int argc,char *argv[])
{
 FILE *p=NULL,*q=NULL;
 char  *ptr;
 ptr=(char *)malloc(sizeof(char)*16);//如果没开辟空间的话会出现段错误。

 if(argc<3)
  printf("usage:copy file1 to file2");
 if((p= fopen(argv[1],"r"))==NULL)
  printf("open file1 fail");
 else
 {  
        if((q=fopen(argv[2],"a+"))==NULL)
   printf("open file: %s fail",argv[2]);
   else
   while((!feof(p))&&(fread((void *)ptr,16,1,p)==1))
   { 
            if(fwrite((void *)ptr,16,1,q)!=1)
   printf("write file :%s error",argv[2]);
   }
 }

 close(p);
       close(q);
 free(ptr);
}

 

 

 

系统调用:

             
              #include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>

int main(int argc,char *argv[])
{
 int fd,to_fd;
 char buf[128]={0};
 int readbyte,writebyte;
        char *ptr;

 if(argc<3)

 {
  printf("usage:copy file1 to file2/n");
  exit(-1);
 }
 fd=open(argv[1],O_RDONLY);
 if(fd<0)
  printf("open file:%s error/n",argv[1]);
 to_fd=open(argv[2],O_RDWR|O_APPEND|O_CREAT,S_IRWXU);
 if(to_fd<0)
  
 {
  printf("open file:%s error/n",argv[2]);
  exit(-2);
 }
 while(readbyte=read(fd,buf,128))
 {
  if(readbyte==-1)
  {
   printf("read file:%s error/n",argv[2]);
   exit(-3);
  }
  else
  {
   ptr=buf;
          if((writebyte=write(to_fd,ptr,readbyte)==-1))
   {
    printf("wtite file:%s error/n",argv[2]);
    exit(-4);
   }
  }
 } 
 close(fd);
 close(to_fd);

free(ptr);
}