-
Notifications
You must be signed in to change notification settings - Fork 0
/
mycp.c
78 lines (69 loc) · 1.84 KB
/
mycp.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#define BUFSIZE 1024
int copy(const char *file1, const char *file2){
/*copy contents of file1 to file2, ignore the hole*/
int fd1, fd2, num, i;
int base, probe;
char buf[BUFSIZE];
/*open the source and target files*/
if((fd1 = open(file1, O_RDWR)) == -1){
printf("Error opening %s for copying\n", file1);
return -1;
}
if((fd2 = open(file2, O_RDWR|O_APPEND|O_CREAT|O_TRUNC)) == -1){
printf("Error creating %s to copy\n", file2);
return -1;
}
do{
memset(buf, '\0', BUFSIZE);
if((num = read(fd1, buf, BUFSIZE)) == -1){
printf("Error reading %s for copying\n", file1);
return -1;
}
/*clear all "holes"('\0') in the buf array*/
base =0;
for(i=0; i<num; i++){
if(buf[i] != '\0'){
base++;
}
else{
probe = i+1;
while(probe < num){
if(buf[probe] != '\0'){
buf[base] = buf[probe];
i = probe;
base++;
break;
}
probe++;
}
if(probe == num){
break;
}
}
}
/*write the buf into file2*/
if((num = write(fd2, buf, base)) == -1){
printf("Error writing %s to copy\n", file2);
return -1;
}
}
while(num >0);
close(fd1);
close(fd2);
return 0;
}
int main(int argc, char *argv[]){
char *file1, *file2;
if(argc != 3){
printf("parameter error!\n");
return -1;
}
file1 = argv[1];
file2 = argv[2];
return copy(file1, file2);
}