短路原则的实例

短路原则的实例

短路原则妙用实例

程序功能:将一个文件A的内容进行均分,将前一半内容复制到文件B,后一半内容复制到文件C。
短路原则使用:代码第29行。

  6 int main(int argc, char * argv[])
  7 {
  8     int outfd_one, outfd_two, infd;
  9     int end = 0;
 10     char buf[1024] = {0};
 11     int size = 0;
 12     if((infd = open("./1.txt", O_RDONLY)) == -1){
 13         perror("open in file fail");
 14         return -1;
 15     }
 16     if((outfd_one = open("./2.txt", O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)) == -1){
 17         perror("open out file fail");
 18         return -1;
 19     }
 20     if((outfd_two = open("./3.txt", O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)) == -1){
 21         perror("open out file fail");
 22         return -1;
 23     }
 24     lseek(infd, 0, SEEK_SET);
 25     end = lseek(infd, 0, SEEK_END);
 26     lseek(infd, 0, SEEK_SET);
 27     end /= 2;
 28     size = 1024;
 29     while(end / 1024 != 0 || (size = end % 1024) != 0){
 30         if(read(infd, buf, size) == -1){
 31             perror("read fail");
 32             return -1;
 33         }
 34         write(outfd_one, buf, size);
 35         end -= size;
 36     }
 37 
 38     size = 0;
 39     while((size = read(infd, buf, 1024)) != 0){
 40         if(size == -1){
 41             perror("read fail");
 42             return -1;
 43         }
 44         write(outfd_two, buf, size);
 45     }
 46 
 47 
 48     close(infd);
 49     close(outfd_one);
 50     close(outfd_two);
 51 }                                     

说明:
(1)代码未遵循代码规范,如拷贝使用,请自行更改以避免不规范带来的BUG。
(2)实现思路属作者原创,在使用中,如果发现问题,请及时沟通。
(3)如有雷同,纯属巧合。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值