-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcopyfile.c
executable file
·62 lines (55 loc) · 1.37 KB
/
copyfile.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
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#define BUFFER_SIZE 1024
int main(int argc,char **argv) {
int from_fd,to_fd;
int bytes_read,bytes_write;
char buffer[BUFFER_SIZE];
char *ptr;
if(argc != 3) {
fprintf(stderr,"Usage:%s fromfile tofile\n\a",argv[0]);
exit(1);
}
//打开源文件
if((from_fd = open(argv[1],O_RDONLY)) == -1) {
fprintf(stderr,"Open %s Error:%s\n",argv[1],strerror(errno));
exit(-1);
}
//创建目的文件
if((to_fd = open(argv[2],O_WRONLY | O_CREAT,S_IRUSR | S_IWUSR)) == -1) {
fprintf(stderr,"Open %s Error:%s\n",argv[2],strerror(errno));
exit(1);
}
//经典拷贝文件代码
while(bytes_read = read(from_fd,buffer,BUFFER_SIZE)) {
//一个致命错误发生了
if((bytes_read == -1) && (errno != EINTR))
break;
else if(bytes_read > 0) {
ptr = buffer;
while(bytes_write = write(to_fd,ptr,bytes_read)) {
//一个致命错误发生了
if((bytes_write == -1) && (errno != EINTR))
break;
//写完了所有读的字节
else if(bytes_write == bytes_read)
break;
//只写了一部分,继续写
else if(bytes_write > 0) {
ptr += bytes_write;
bytes_read -= bytes_write;
}
}
//写得时候发生致命错误
if(bytes_write == -1)
break;
}
}
return 0;
}