Linux 拷贝文件函数:不知道这个对不对,转载了再说

Linux 拷贝文件函数
2007-12-17 10:56
1 /*
2 * Copy a (real) file to another (real) file.
3 * file can be a regular file or a simlink
4 */
5 int create_copy_file(const char *source, const char *target)
6 {
7         struct stat src_stat;
8
9         if (lstat(source, &src_stat) == -1)
10                 return -1;
11
12         if (S_ISLNK(src_stat.st_mode)) {
13                 char lnk[1024];
14                 int lnk_size;
15                 if ((lnk_size = readlink(source, lnk, 1023)) == -1)
16                         return -2;
17                 lnk[lnk_size] = '\0';
18                 if (symlink(lnk, target) == -1)
19                         return -3;
20         } else if (S_ISREG(src_stat.st_mode)) {
21                 int src, dst;
22                 int rsize;
23                 char buf[1024];
24                 if ((src = open(source, O_RDONLY)) == -1) {
25                         close(dst);
26                         return -4;
27                 }
28                 if ((dst = creat(target, src_stat.st_mode)) == -1)
29                         return -5;
30                 while ((rsize = read(src, buf, 1024))) {
31                         if (rsize == -1 && errno == EINTR)
32                                 continue ;
33                         if (rsize == -1) {
34                                 close(src);
35                                 close(dst);
36                                 return -6;
37                         }
38                         while (write(dst, buf, rsize) == -1)
39                                 if (errno != EINTR) {
40                                 close(src);
41                                 close(dst);
42                                 return -7;
43                         }
44                 }
45                 close(src);
46                 close(dst);
47         } else {
48                 return -8;
49         }
50         return 0;
51 }

你可能感兴趣的:(C,unix/linux)