《UNIX环境高级编程》读书笔记之文件IO(2)

1.编写一个与3.12节dup2功能相同的函数。

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>

int main(int argc,char *argv[]) {
   int i;
   int fd_src,fd_dest;
   
   if(argc != 3)
   {
     fprintf(stderr,"usage %s src dest\n",argv[0]);
     return -1;
   }
       
   fd_src = atoi(argv[1]);
   fd_dest = atoi(argv[2]);
   if (fd_src <= 0 || fd_dest <= 0 || fd_src > 256 || fd_dest > 256)
    {
      fprintf(stderr,"fd should be greater then 0 and less or equal 256\n");
      return -1;
    }
      
   
   if(fd_src == fd_dest)
    {	
	fprintf(stdout,"the new fd is %d\n",fd_dest);
	return 0; 
    }
     
   if(dup(fd_src) == -1)
    {
      fprintf(stderr,"the fd is not open\n");
      return -1;     
    }
   
   int fdarray[fd_dest];
   int index;
   close(fd_dest);
   for(index = 0;index < fd_dest;index++)
	{
	   fdarray[index] = dup(fd_src);
           if(fdarray[index] == -1)
	{
	  fprintf(stderr,"dup error\n");
          return -1;
	}    
           if(fdarray[index] == fd_dest)
              fprintf(stdout,"dup success!the new fd is %d\n",fd_dest);
	}
   for(i = 0;i < index;i++)
       close(fdarray[i]);
   return 0;
}



2.编程实现cp功能。

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc,char * argv[])
{
   if(argc != 3)
  {
    fprintf(stderr,"usage:%s file1 file2\n",argv[0]);
    return -1;
  }
  
  int fd1 = open(argv[1],O_RDONLY);
  if(fd1 == -1)
 {
    fprintf(stderr,"can not open file %s\n ",argv[1]);
    return -1;
 }
  
  int fd2 = open(argv[2],O_WRONLY | O_CREAT,0664);
  char buffer[4096];
  int n;

  while((n = read(fd1,buffer,4096)) > 0)
       write(fd2,buffer,n);

  close(fd1);
  close(fd2);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值