本程序实现数据拷贝。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFSIZE 4096

int main(int argc,char* argv[])
{
    if(argc!=1&&argc!=3)
    {
     fprintf(stderr,"Invalid argument number\n");
     exit(1);
    }
    int from,to;
    int n;
    char buf[BUFSIZE];
    if(argc==1)
    {
      from = STDIN_FILENO;
      to = STDOUT_FILENO;
    }    
    else
    {
      if((from = open(argv[1], O_RDONLY))==-1)
      {
        fprintf(stderr,"open %s error\n",argv[1]);
        exit(2);
      }
      if((to = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR))==-1)
      {
        fprintf(stderr,"open %s error\n",argv[2]);
        exit(3);
      }
    }
    
    while ((n = read(from, buf, BUFSIZE)) > 0)
    {
      if (write(to, buf, n) != n)
      {
        fprintf(stderr, "write error\n");
        exit(4);
      }
      if (n < 0) 
      {
        fprintf(stderr, "read error\n");
        exit(5);
      }
    }
     close(from);
     close(to);
     exit(0);
}


相关文章:

  • 2022-02-26
  • 2021-12-18
  • 2022-12-23
  • 2021-11-23
  • 2022-01-19
  • 2021-05-18
  • 2022-01-06
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-26
  • 2021-06-08
  • 2021-10-05
  • 2021-10-25
相关资源
相似解决方案