短路原则的实例
短路原则妙用实例
程序功能:将一个文件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)如有雷同,纯属巧合。